a `@s(dZddlZddlmZmZddlZddlmZm Z m Z ddl m Z m Z zeWneyfeZYn0edZGdddeZdLd d ZdMd d ZdNd dZdOddZdefddZefddZddZdefddZdPddZefddZefdd Zefd!d"Zefd#d$Z efd%d&Z!efd'd(Z"d)d*Z#d+d,Z$deddfd-d.Z%Gd/d0d0e&Z'dedd1ddfd2d3Z(dedd1ddfd4d5Z)deddfd6d7Z*dedfd8d9Z+Gd:d;d;e,Z-efdd?Z/d@Z0dAZ1dBe0Z2dCe1Z3dDZ4e5dEe2e3e4fZ6dFdGZ7dHdIZ8GdJdKdKe9Z:dS)Qa babel.numbers ~~~~~~~~~~~~~ Locale dependent formatting and parsing of numeric data. The default locale for the functions in this module is determined by the following environment variables, in that order: * ``LC_NUMERIC``, * ``LC_ALL``, and * ``LANG`` :copyright: (c) 2013-2021 by the Babel Team. :license: BSD, see LICENSE for more details. N)datedatetime)default_localeLocale get_global)decimal string_types LC_NUMERICc@seZdZdZddZdS)UnknownCurrencyErrorzRException thrown when a currency is requested for which no data is available. cCst|d|||_dS)zkCreate the exception. :param identifier: the identifier string of the unsupported currency zUnknown currency %r.N) Exception__init__ identifier)selfr r1/usr/lib/python3.9/site-packages/babel/numbers.pyr +szUnknownCurrencyError.__init__N)__name__ __module__ __qualname____doc__r rrrrr 'sr cCs&|rt|j}ntd}t|S)aM Return a `set` of normalized currency codes. .. versionadded:: 2.5.0 :param locale: filters returned currency codes by the provided locale. Expected to be a locale instance or code. If no locale is provided, returns the list of all currencies from all locales. Zall_currencies)rparse currencieskeysrset)localerrrrlist_currencies5s rcCs|t|vrt|dS)a Check the currency code is recognized by Babel. Accepts a ``locale`` parameter for fined-grained validation, working as the one defined above in ``list_currencies()`` method. Raises a `UnknownCurrencyError` exception if the currency is unknown to Babel. N)rr currencyrrrrvalidate_currencyGs rcCs:|rt|tsdSzt||Wnty4YdS0dS)zy Returns `True` only if a currency is recognized by Babel. This method always return a Boolean and never raise. FT) isinstancerrr rrrr is_currencySs rcCs$t|tr|}t||s dS|S)zReturns the normalized sting of any currency code. Accepts a ``locale`` parameter for fined-grained validation, working as the one defined above in ``list_currencies()`` method. Returns None if the currency is unknown to Babel. N)rrupperrrrrrnormalize_currencyas   r!cCsHt|}|dur:||}|jd}||vr:|||S|j||S)aReturn the name used by the locale for the specified currency. >>> get_currency_name('USD', locale='en_US') u'US Dollar' .. versionadded:: 0.9.4 :param currency: the currency code. :param count: the optional count. If provided the currency name will be pluralized to that number if possible. :param locale: the `Locale` object or locale identifier. NZcurrency_names_plural)rr plural_form_datarget)rcountrlocr"Z plural_namesrrrget_currency_nameps    r'cCst|j||S)zReturn the symbol used by the locale for the specified currency. >>> get_currency_symbol('USD', locale='en_US') u'$' :param currency: the currency code. :param locale: the `Locale` object or locale identifier. )rrZcurrency_symbolsr$rrrrget_currency_symbols r(cCstd}|||ddS)zReturn currency's precision. Precision is the number of decimals found after the decimal point in the currency's format pattern. .. versionadded:: 2.5.0 :param currency: the currency code. Zcurrency_fractionsZDEFAULTr)rr$)rZ precisionsrrrget_currency_precisions r)cCsNt|}|dur@||}z|jd|WSty>Yn0|jddS)aV Return the unit pattern used for long display of a currency value for a given locale. This is a string containing ``{0}`` where the numeric part should be substituted and ``{1}`` where the currency long display name should be substituted. >>> get_currency_unit_pattern('USD', locale='en_US', count=10) u'{0} {1}' .. versionadded:: 2.7.0 :param currency: the currency code. :param count: the optional count. If provided the unit pattern for that number will be returned. :param locale: the `Locale` object or locale identifier. NZcurrency_unit_patternsother)rrr"r# LookupError)rr%rr&r"rrrget_currency_unit_patterns   r,TFcstd}durtnttr,dur:nttrL||d}fdd}g} |D]b\} } } } | rt| } | rt| } | r|s| sr|rr|| | rr|r| | | | | dqr| | qr| S)asReturns the list of currencies for the given territory that are valid for the given date range. In addition to that the currency database distinguishes between tender and non-tender currencies. By default only tender currencies are returned. The return value is a list of all currencies roughly ordered by the time of when the currency became active. The longer the currency is being in use the more to the left of the list it will be. The start date defaults to today. If no end date is given it will be the same as the start date. Otherwise a range can be defined. For instance this can be used to find the currencies in use in Austria between 1995 and 2011: >>> from datetime import date >>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1)) ['ATS', 'EUR'] Likewise it's also possible to find all the currencies in use on a single date: >>> get_territory_currencies('AT', date(1995, 1, 1)) ['ATS'] >>> get_territory_currencies('AT', date(2011, 1, 1)) ['EUR'] By default the return value only includes tender currencies. This however can be changed: >>> get_territory_currencies('US') ['USD'] >>> get_territory_currencies('US', tender=False, non_tender=True, ... start_date=date(2014, 1, 1)) ['USN', 'USS'] .. versionadded:: 2.0 :param territory: the name of the territory to find the currency for. :param start_date: the start date. If not given today is assumed. :param end_date: the end date. If not given the start date is assumed. :param tender: controls whether tender currencies should be included. :param non_tender: controls whether non-tender currencies should be included. :param include_details: if set to `True`, instead of returning currency codes the return value will be dictionaries with detail information. In that case each dictionary will have the keys ``'currency'``, ``'from'``, ``'to'``, and ``'tender'``. Zterritory_currenciesNrcs |dus|ko|dup|kSNr)startendend_date start_daterr _is_activesz,get_territory_currencies.._is_active)rfromtotender) rdate_Ztodayr datetime_rr$r append) territoryr2r1r6Z non_tenderZinclude_detailsrZcursr3resultZ currency_coder.r/Z is_tenderrr0rget_territory_currenciessB4     r<cCst|jddS)zReturn the symbol used by the locale to separate decimal fractions. >>> get_decimal_symbol('en_US') u'.' :param locale: the `Locale` object or locale identifier r.rrZnumber_symbolsr$rrrrget_decimal_symbolsr@cCst|jddS)zReturn the plus sign symbol used by the current locale. >>> get_plus_sign_symbol('en_US') u'+' :param locale: the `Locale` object or locale identifier ZplusSign+r>r?rrrget_plus_sign_symbol#srBcCst|jddS)zReturn the plus sign symbol used by the current locale. >>> get_minus_sign_symbol('en_US') u'-' :param locale: the `Locale` object or locale identifier Z minusSign-r>r?rrrget_minus_sign_symbol.srDcCst|jddS)zReturn the symbol used by the locale to separate mantissa and exponent. >>> get_exponential_symbol('en_US') u'E' :param locale: the `Locale` object or locale identifier Z exponentialEr>r?rrrget_exponential_symbol9srFcCst|jddS)zReturn the symbol used by the locale to separate groups of thousands. >>> get_group_symbol('en_US') u',' :param locale: the `Locale` object or locale identifier group,r>r?rrrget_group_symbolDsrIcCstdtt||dS)afReturn the given number formatted for a specific locale. >>> format_number(1099, locale='en_US') u'1,099' >>> format_number(1099, locale='de_DE') u'1.099' .. deprecated:: 2.6.0 Use babel.numbers.format_decimal() instead. :param number: the number to format :param locale: the `Locale` object or locale identifier z+Use babel.numbers.format_decimal() instead.r?)warningswarnDeprecationWarningformat_decimal)numberrrrr format_numberOs rOcCs$|}|jdkrdSt|jS)zReturn maximum precision of a decimal instance's fractional part. Precision is extracted from the fractional part only. r) normalizeZas_tupleZexponentabs)rNZ decimal_tuplerrrget_decimal_precisionds  rRcCstd| S)z>> format_decimal(1.2345, locale='en_US') u'1.234' >>> format_decimal(1.2346, locale='en_US') u'1.235' >>> format_decimal(-1.2346, locale='en_US') u'-1.235' >>> format_decimal(1.2345, locale='sv_SE') u'1,234' >>> format_decimal(1.2345, locale='de') u'1,234' The appropriate thousands grouping and the decimal separator are used for each locale: >>> format_decimal(12345.5, locale='en_US') u'12,345.5' By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the `decimal_quantization` parameter: >>> format_decimal(1.2346, locale='en_US') u'1.235' >>> format_decimal(1.2346, locale='en_US', decimal_quantization=False) u'1.2346' >>> format_decimal(12345.67, locale='fr_CA', group_separator=False) u'12345,67' >>> format_decimal(12345.67, locale='en_US', group_separator=True) u'12,345.67' :param number: the number to format :param format: :param locale: the `Locale` object or locale identifier :param decimal_quantization: Truncate and round high-precision numbers to the format pattern. Defaults to `True`. :param group_separator: Boolean to switch group separator on/off in a locale's number format. decimal_quantizationgroup_separator)rrdecimal_formatsr$ parse_patternapplyrNformatrrWrXpatternrrrrMws*  rMc@seZdZdZdS)UnknownCurrencyFormatErrorz>Exception raised when an unknown currency format is requested.N)rrrrrrrrr_sr_Zstandardc Csz|dkrt|||||||dSt|}|r6t|}n.z|j|}Wntybtd|Yn0|j||||||dS)u Return formatted currency value. >>> format_currency(1099.98, 'USD', locale='en_US') u'$1,099.98' >>> format_currency(1099.98, 'USD', locale='es_CO') u'US$\xa01.099,98' >>> format_currency(1099.98, 'EUR', locale='de_DE') u'1.099,98\xa0\u20ac' The format can also be specified explicitly. The currency is placed with the '¤' sign. As the sign gets repeated the format expands (¤ being the symbol, ¤¤ is the currency abbreviation and ¤¤¤ is the full name of the currency): >>> format_currency(1099.98, 'EUR', u'¤¤ #,##0.00', locale='en_US') u'EUR 1,099.98' >>> format_currency(1099.98, 'EUR', u'#,##0.00 ¤¤¤', locale='en_US') u'1,099.98 euros' Currencies usually have a specific number of decimal digits. This function favours that information over the given format: >>> format_currency(1099.98, 'JPY', locale='en_US') u'\xa51,100' >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES') u'1.099,98' However, the number of decimal digits can be overriden from the currency information, by setting the last parameter to ``False``: >>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False) u'\xa51,099.98' >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False) u'1.099,98' If a format is not specified the type of currency format to use from the locale can be specified: >>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard') u'\u20ac1,099.98' When the given currency format type is not available, an exception is raised: >>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown') Traceback (most recent call last): ... UnknownCurrencyFormatError: "'unknown' is not a known currency format type" >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False) u'$101299.98' >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True) u'$101,299.98' You can also pass format_type='name' to use long display names. The order of the number and currency name, along with the correct localized plural form of the currency name, is chosen according to locale: >>> format_currency(1, 'USD', locale='en_US', format_type='name') u'1.00 US dollar' >>> format_currency(1099.98, 'USD', locale='en_US', format_type='name') u'1,099.98 US dollars' >>> format_currency(1099.98, 'USD', locale='ee', format_type='name') u'us ga dollar 1,099.98' By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the `decimal_quantization` parameter: >>> format_currency(1099.9876, 'USD', locale='en_US') u'$1,099.99' >>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False) u'$1,099.9876' :param number: the number to format :param currency: the currency code :param format: the format string to use :param locale: the `Locale` object or locale identifier :param currency_digits: use the currency's natural number of decimal digits :param format_type: the currency format type to use :param decimal_quantization: Truncate and round high-precision numbers to the format pattern. Defaults to `True`. :param group_separator: Boolean to switch group separator on/off in a locale's number format. name)r]rcurrency_digitsrWrXz&%r is not a known currency format typerrarWrX)_format_currency_long_namerrrZZcurrency_formatsKeyErrorr_r[) rNrr]rra format_typerWrXr^rrrformat_currencys$Z    rfc Csxt|}t|trt|}n|}t|||d} t|||d} |sN|j|}t |} | j ||||||d} | | | S)N)r%rrb) rrrrfloatr,r'rYr$rZr[r]) rNrr]rrarerWrXZnumber_nZ unit_patternZ display_namer^Z number_partrrrrcs    rccCs4t|}|s|j|}t|}|j||||dS)uDReturn formatted percent value for a specific locale. >>> format_percent(0.34, locale='en_US') u'34%' >>> format_percent(25.1234, locale='en_US') u'2,512%' >>> format_percent(25.1234, locale='sv_SE') u'2\xa0512\xa0%' The format pattern can also be specified explicitly: >>> format_percent(25.1234, u'#,##0‰', locale='en_US') u'25,123‰' By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the `decimal_quantization` parameter: >>> format_percent(23.9876, locale='en_US') u'2,399%' >>> format_percent(23.9876, locale='en_US', decimal_quantization=False) u'2,398.76%' >>> format_percent(229291.1234, locale='pt_BR', group_separator=False) u'22929112%' >>> format_percent(229291.1234, locale='pt_BR', group_separator=True) u'22.929.112%' :param number: the percent number to format :param format: :param locale: the `Locale` object or locale identifier :param decimal_quantization: Truncate and round high-precision numbers to the format pattern. Defaults to `True`. :param group_separator: Boolean to switch group separator on/off in a locale's number format. rV)rrZpercent_formatsr$rZr[r\rrrformat_percent>s'  rhcCs2t|}|s|j|}t|}|j|||dS)aReturn value formatted in scientific notation for a specific locale. >>> format_scientific(10000, locale='en_US') u'1E4' The format pattern can also be specified explicitly: >>> format_scientific(1234567, u'##0.##E00', locale='en_US') u'1.23E06' By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the `decimal_quantization` parameter: >>> format_scientific(1234.9876, u'#.##E0', locale='en_US') u'1.23E3' >>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False) u'1.2349876E3' :param number: the number to format :param format: :param locale: the `Locale` object or locale identifier :param decimal_quantization: Truncate and round high-precision numbers to the format pattern. Defaults to `True`. )rW)rrZscientific_formatsr$rZr[)rNr]rrWr^rrrformat_scientificms  rics"eZdZdZdfdd ZZS)NumberFormatErrorz>Exception raised when a string cannot be parsed into a number.Ncstt||||_dSr-)superrjr suggestions)rmessagerl __class__rrr szNumberFormatError.__init__)N)rrrrr __classcell__rrrnrrjsrjcCs:zt|t|dWSty4td|Yn0dS)aSParse localized number string into an integer. >>> parse_number('1,099', locale='en_US') 1099 >>> parse_number('1.099', locale='de_DE') 1099 When the given string cannot be parsed, an exception is raised: >>> parse_number('1.099,98', locale='de') Traceback (most recent call last): ... NumberFormatError: '1.099,98' is not a valid number :param string: the string to parse :param locale: the `Locale` object or locale identifier :return: the parsed number :raise `NumberFormatError`: if the string can not be converted to a number z%r is not a valid numberN)intreplacerI ValueErrorrj)stringrrrr parse_numbers rvc CsXt|}t|}t|}|sB|dkrB||vrBd|vrB|d|}zt||d|d}Wn tjytd|Yn0|rT||vrTt ||dd}||krT| d||krTzt||d|d}Wn,tjytd ||f|gd YnL0t ||dd}||kr:td ||f|gd ntd |||f||gd |S) akParse localized decimal string into a decimal. >>> parse_decimal('1,099.98', locale='en_US') Decimal('1099.98') >>> parse_decimal('1.099,98', locale='de') Decimal('1099.98') >>> parse_decimal('12 345,123', locale='ru') Decimal('12345.123') When the given string cannot be parsed, an exception is raised: >>> parse_decimal('2,109,998', locale='de') Traceback (most recent call last): ... NumberFormatError: '2,109,998' is not a valid decimal number If `strict` is set to `True` and the given string contains a number formatted in an irregular way, an exception is raised: >>> parse_decimal('30.00', locale='de', strict=True) Traceback (most recent call last): ... NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'? >>> parse_decimal('0.00', locale='de', strict=True) Traceback (most recent call last): ... NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'? :param string: the string to parse :param locale: the `Locale` object or locale identifier :param strict: controls whether numbers formatted in a weird way are accepted or rejected :raise NumberFormatError: if the string can not be converted to a decimal number   rqr=z %r is not a valid decimal numberF)rrW0z?%r is not a properly formatted decimal number. Did you mean %r?)rlzL%r is not a properly formatted decimal number. Did you mean %r? Or maybe %r?) rrrIr@rsrrTZInvalidOperationrjrMrstrip) rurstrictZ group_symbolZdecimal_symbolparsedZproperZ parsed_altZ proper_altrrr parse_decimals\%      r}z [^0-9@#.,]z [0-9@#.,E+]z(?P(?:'[^']*'|%s)*)z(?P%s*)z(?P.*)z%s%s%scCsjt|}|d}|dkrdS||d}|d| dd}|dkrR||fS|||d}||fS)zParse primary and secondary digit grouping >>> parse_grouping('##') (1000, 1000) >>> parse_grouping('#,###') (3, 3) >>> parse_grouping('#,####,###') (3, 4) rH)rN)lenrfind)pwidthZg1Zg2rrrparse_groupings   rc Cs4t|tr|Sdd}|}d|vrP|dd\}}||\}}}||\}}} n||\}}}d|}|} d|vr|dd\}} nd} d|vrd |vrd |vrtd d |vr|d d\} } n|} d } d d} | | }| | }| r| d}| d} | | }nd}d}t| }t|||f|| f|||||S)zParse number format patternscSs&t|}|durtd||S)NzInvalid number pattern %r) number_researchrtgroups)r^rvrrr _match_number)s  z$parse_pattern.._match_number;rrCrEN@r=ryz5Significant digit patterns can not contain "@" or "0"rqcSsVd}}|D]@}|dvr*|d7}|d7}q |dkr<|d7}q |dkrHq q qNq ||fS)z(Calculate the min and max allowed digitsrz@0r#rHr)rminmaxcrrrparse_precisionHs  z&parse_pattern..parse_precisionrA)r NumberPatternsplitrtrsplit startswithlstripr)r^rZ pos_patternZ neg_patternZ pos_prefixrNZ pos_suffixZ neg_prefix_Z neg_suffixexpZintegerZfractionrint_prec frac_precexp_plusexp_precgroupingrrrrZ$sH     rZc@sXeZdZddZddZddZddZdd d Zd dZddZ ddZ dddZ d S)rc Cs>||_||_||_||_||_||_||_||_||_ dSr-) r^prefixsuffixrrrrr compute_scalescale) rr^rrrrrrrrrrr iszNumberPattern.__init__cCsdt|j|jfS)Nz<%s %r>)typerr^)rrrr__repr__vszNumberPattern.__repr__cCs>d}dd|j|jvr d}ndd|j|jvr:d}|S)uReturn the scaling factor to apply to the number before rendering. Auto-set to a factor of 2 or 3 if presence of a ``%`` or ``‰`` sign is detected in the prefix or suffix of the pattern. Default is to not mess with the scale at all and keep it to 0. r%rqru‰)joinrr)rrrrrrys zNumberPattern.compute_scalecCsv|}|t|}tdt|jgd}||}|t| }d}|dkrVt|}n|jrdt|}t|}|||fS)zG Returns normalized scientific notation components of a value. rrqr) adjustedrUrrrrDrrBrQ)rvaluerrZ lead_shiftexp_signrrrscientific_notation_elementss  z*NumberPattern.scientific_notation_elementsNTc Cst|tjstt|}||j}t|}t| }|j rV| ||\}} } |rlt dt|} n|r|rt|fd} n|j} |r|j r| dkr| dt| dt|gf} |j rd|||| |t|| |t| |j d|j d|g} nnd|jvr\|||jd|jd} | d\}}}||dd |} |rl| t||7} n|||| |} d|j|| |j|g}d |vr|d t|||}|d | }|d t!||}|S) aRenders into a string a number following the defined pattern. Forced decimal quantization is active by default so we'll produce a number string that is strictly following CLDR pattern definitions. :param value: The value to format. If this is not a Decimal object, it will be cast to one. :type value: decimal.Decimal|float|int :param locale: The locale to use for formatting. :type locale: str|babel.core.Locale :param currency: Which currency, if any, to format as. :type currency: str|None :param currency_digits: Whether or not to use the currency's precision. If false, the pattern's precision is used. :type currency_digits: bool :param decimal_quantization: Whether decimal numbers should be forcibly quantized to produce a formatted output strictly matching the CLDR definition for the locale. :type decimal_quantization: bool :param force_frac: DEPRECATED - a forced override for `self.frac_prec` for a single formatting invocation. :return: Formatted decimal string. :rtype: str z@The force_frac parameter to NumberPattern.apply() is deprecated.r)rrrrrqrr=r¤u¤¤¤u¤¤)"rrrTstrscalebrrrZ is_signedrQrPrrrJrKrLr)rrrRr_quantize_valuerF _format_intr^_format_significantr partitionr@rrrsr'r r()rrrrrarW force_fracrXZ is_negativerrrrNtextasepbZretvalrrrr[s\#        zNumberPattern.applyc Cs|}|d|}t||td}|dkrF|d| }nh|d| }t|} | t|| d} dj|pxddt |dd || | || d dd d}|S)Nrrryz-{intpart}.{pad:0<{fill}}{fracpart}{fracextra}rq)intpartZpadfillZfracpartZ fracextrar=) rrrquantizerrTrrr]rrz) rrZminimumZmaximumrrdigitsr;rijrrrrs$  z!NumberPattern._format_significantc Cszt|}||kr d|||}|jd}d}t|}t||krr||| d|}|d| }|jd}q6||S)Nryrrqr)rrrI) rrrrrrZgsizeretsymbolrrrr1s   zNumberPattern._format_intc Csjt|d}||}d|d\}}} |} |rP|||jd|jd|} | || p\d||} | S)Nrz{:f}r=rry)rUrr]rrr _format_frac) rrrrrXZquantumZroundedrrrZ integer_partrNrrrr>s  zNumberPattern._quantize_valuecCs|p|j\}}t||kr.|d|t|7}|dksJ|dkrNt|dkrNdSt||krt|ddkrt|dd}qNt||S)Nryrrqr~)rrrrr@)rrrrrrrrrrHs zNumberPattern._format_frac)NTTNT)N) rrrr rrrr[rrrrrrrrrgs  |  r)N)N)N)N)NNTFF);rrerrr7r8rJZ babel.corerrrZ babel._compatrrZlong NameErrorrrr r r rrrr!r'r(r)r,r<r@rBrDrFrIrOrRrUrMrdr_rfrcrhrirtrjrvr}Z PREFIX_ENDZ NUMBER_TOKENZPREFIX_PATTERNZNUMBER_PATTERNZSUFFIX_PATTERNcompilerrrZobjectrrrrrst       Z   2 n % 0 # P C