o l: ^@s&dZddlZddlmZmZddlZddlmZm Z m Z ddl m Z m Z zeWn ey3eZYnwedZGdddeZdLd d ZdLd d ZdLd dZdLddZdefddZefddZddZdefddZ   dMddZefddZefdd Zefd!d"Zefd#d$Z efd%d&Z!efd'd(Z"d)d*Z#d+d,Z$dedfd-d.Z%Gd/d0d0e&Z'dedd1dfd2d3Z(dedd1dfd4d5Z)dedfd6d7Z*dedfd8d9Z+Gd:d;d;e,Z-efdd?Z/d@Z0dAZ1dBe0Z2dCe1Z3dDZ4e5dEe2e3e4fZ6dFdGZ7dHdIZ8GdJdKdKe9Z:dS)Na 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-2019 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 r//usr/lib/python3/dist-packages/babel/numbers.pyr +s zUnknownCurrencyError.__init__N)__name__ __module__ __qualname____doc__r rrrrr 's r cCs,|rt|j}t|Std}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. all_currencies)rparse currencieskeysrset)localerrrrlist_currencies5s  rcCs|t|vr t|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 rcCs8|rt|ts dSzt||WdStyYdSw)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  r cCs$t|tr |}t||sdS|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)rrupperr rrrrnormalize_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. Ncurrency_names_plural)rr plural_form_datarget)rcountrlocr$ 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. )rrcurrency_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. currency_fractionsDEFAULTr)rr&)r precisionsrrrget_currency_precisions r0cCsNt|}|dur ||}z|jd|WStyYnw|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. Ncurrency_unit_patternsother)rrr$r% LookupError)rr'rr(r$rrrget_currency_unit_patterns   r4TFcstd}dur tn ttrdurn ttr&||d}fdd}g} |D]1\} } } } | rEt| } | rKt| } | rO|sS| sj|rj|| | rj|re| | | | | dq9| | q9| 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'``. territory_currenciesNrcs |dus|ko|dup|kSNr)startendend_date start_daterr _is_activesz,get_territory_currencies.._is_active)rfromtotender) rdate_todayr datetime_rr&r!append) territoryr;r:r? non_tenderinclude_detailsrcursr<result currency_coder7r8 is_tenderrr9rget_territory_currenciessD4    rKcCt|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.rrnumber_symbolsr&rrrrget_decimal_symbolrQcCrL)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 plusSign+rNrPrrrget_plus_sign_symbol#rRrUcCrL)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 minusSign-rNrPrrrget_minus_sign_symbol.rRrXcCrL)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 exponentialErNrPrrrget_exponential_symbol9rRr[cCrL)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,rNrPrrrget_group_symbolDrRr^cCstdtt||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.rP)warningswarnDeprecationWarningformat_decimal)numberrrrr format_numberOs  rdcCs4t|tjsJ|}|jdkrdSt|jS)zReturn maximum precision of a decimal instance's fractional part. Precision is extracted from the fractional part only. r)rrDecimal normalizeas_tupleexponentabs)rc decimal_tuplerrrget_decimal_precisionds    rkcCs&t|tttjfs Jtd| 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' :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`. decimal_quantization)rrdecimal_formatsr& parse_patternapplyrcformatrrspatternrrrrbws $ rbc@seZdZdZdS)UnknownCurrencyFormatErrorz>Exception raised when an unknown currency format is requested.N)rrrrrrrrrzsrzstandardcCsr|dkrt||||||dSt|}|rt|}nz|j|}Wn ty.td|w|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" 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`. name)rxrcurrency_digitsrsz&%r is not a known currency format typerr}rs)_format_currency_long_namerrrucurrency_formatsKeyErrorrzrv)rcrrxrr} format_typersryrrrformat_currencys&R   rc Csvt|}t|trt|}n|}t|||d}t|||d} |s'|j|}t |} | j |||||d} | | | S)N)r'rr~) rrrrfloatr4r*rtr&rurvrx) rcrrxrr}rrsnumber_n unit_pattern display_namery number_partrrrr s     rcCrq)u Return 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%' :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`. rr)rrpercent_formatsr&rurvrwrrrformat_percent0s  rcCrq)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`. rr)rrscientific_formatsr&rurvrwrrrformat_scientificWs  rcs"eZdZdZdfdd ZZS)NumberFormatErrorz>Exception raised when a string cannot be parsed into a number.Ncstt||||_dSr6)superrr suggestions)rmessager __class__rrr }s zNumberFormatError.__init__r6)rrrrr __classcell__rrrrrzsrcCs2z t|t|dWStytd|w)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 number)rmreplacer^ ValueErrorr)stringrrrr parse_numbers   rc CsBt|}t|}t|}|s!|dkr!||vr!d|vr!|d|}zt||d|d}Wntjy>td|w|r||vrt ||dd}||kr| d||krzt||d|d}Wntjy{td ||f|gd wt ||dd}||krtd ||f|gd td |||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   rrMz %r is not a valid decimal numberF)rrs0z?%r is not a properly formatted decimal number. Did you mean %r?)rzL%r is not a properly formatted decimal number. Did you mean %r? Or maybe %r?) rrr^rQrrreInvalidOperationrrbrstrip) rrstrict group_symboldecimal_symbolparsedproper parsed_alt proper_altrrr parse_decimalsZ %   rz [^0-9@#.,]z [0-9@#.,E+]z(?P(?:'[^']*'|%s)*)z(?P%s*)z(?P.*)z%s%s%scCsjt|}|d}|dkrdS||d}|d| dd}|dkr)||fS|||d}||fS)zParse primary and secondary digit grouping >>> parse_grouping('##') (1000, 1000) >>> parse_grouping('#,###') (3, 3) >>> parse_grouping('#,####,###') (3, 4) r])rN)lenrfind)pwidthg1g2rrrparse_groupings  rc Cs2t|tr|Sdd}|}d|vr(|dd\}}||\}}}||\}}} n ||\}}}d|}|} d|vrB|dd\}} nd} d|vrTd |vrTd |vrTtd d |vra|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_researchrgroups)ryrvrrr _match_numbers  z$parse_pattern.._match_number;rrWrZN@rMrz5Significant digit patterns can not contain "@" or "0"rcSsXd}}|D]!}|dvr|d7}|d7}q|dkr|d7}q|dkr#q||fS||fS)z(Calculate the min and max allowed digitsrz@0r#r]r)rminmaxcrrrparse_precision2s  z&parse_pattern..parse_precisionrT)r NumberPatternsplitrrsplit startswithlstripr)ryr pos_pattern neg_pattern pos_prefixrc pos_suffix neg_prefix_ neg_suffixexpintegerfractionrint_prec frac_precexp_plusexp_precgroupingrrrrusH     ruc@s`eZdZddZddZddZddZ dd d Zd dZddZ ddZ dddZ d S)rc Cs>||_||_||_||_||_||_||_||_||_ dSr6) ryprefixsuffixrrrrr compute_scalescale) rryrrrrrrrrrrr SszNumberPattern.__init__cCsdt|j|jfS)Nz<%s %r>)typerry)rrrr__repr__`szNumberPattern.__repr__cCs@d}dd|j|jvrd}|Sdd|j|jvrd}|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%rru‰)joinrr)rrrrrrcszNumberPattern.compute_scalecCs|}|t|}|dksJtdt|jgd}||}|t| }d}|dkr3t|}n|jr:t|}t|}|||fS)zG Returns normalized scientific notation components of a value. rrr) adjustedrprrrrXrrUri)rvaluerr lead_shiftexp_signrrrscientific_notation_elementsqs   z*NumberPattern.scientific_notation_elementsNTc Cst|tjs tt|}||j}t|}t| }|j r+| ||\}}} |r6t dt|} n|rB|rBt|fd} n|j} |rN|j r\| dkr\| dt| dt|gf} |j r~d|||| t|| |t||j d|j d|g} n4d|jvr|||jd|jd} | d\} }}|| dd |} |r| 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)rrrrrrrMr¤u¤¤¤u¤¤)"rrrestrscalebrrm is_signedrirfrrr_r`rar0rrrkr_quantize_valuer[ _format_intry_format_significantr partitionrQrrrr*r!r,)rrrrr}rs force_frac is_negativerrrrctextasepbretvalrrrrvs^ "       zNumberPattern.applyc Cs|}|d|}t||td}|dkr$|d| }|S|d| }t|} | t|| d} dj|p=ddt |dd || | || d dd d}|S)Nrrrz-{intpart}.{pad:0<{fill}}{fracpart}{fracextra}r)intpartpadfillfracpart fracextrarM) rrrquantizerrerrrxrr) rrminimummaximumrrdigitsrHrijrrrrs&   z!NumberPattern._format_significantc Cst|}||krd|||}|jd}d}t|}t||kr>||| d|}|d| }|jd}t||ks!||S)Nrrrr)rrr^) rrrrrrgsizeretsymbolrrrrs    zNumberPattern._format_intc Cs^t|d}||}d|d\}}}|||jd|jd|||p(d||} | S)Nrz{:f}rMrr)rprrxrrr _format_frac) rrrrquantumroundedrrrrcrrrr's   zNumberPattern._quantize_valuecCs|p|j\}}t||kr|d|t|7}|dks%|dkr't|dkr'dSt||krE|ddkrE|dd}t||krE|ddks3t||S)Nrrrr)rrrmrQ)rrrrrrrrrr0s   zNumberPattern._format_frac)NTTNr6) rrrr rrrrvrrrrrrrrrQs  {  rr6)NNTFF);rrerrr@rBr_ babel.corerrr babel._compatrrrn NameErrorrmr r r rrr r"r*r,r0r4rKrQrUrXr[r^rdrkrprbrrzrrrrrrrr PREFIX_END NUMBER_TOKENPREFIX_PATTERNNUMBER_PATTERNSUFFIX_PATTERNcompilerrruobjectrrrrrsx       Z   , f % ( # P C