Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- lib/python3.10/site-packages/babel/__init__.py +38 -0
- lib/python3.10/site-packages/babel/core.py +1337 -0
- lib/python3.10/site-packages/babel/dates.py +1999 -0
- lib/python3.10/site-packages/babel/languages.py +72 -0
- lib/python3.10/site-packages/babel/lists.py +132 -0
- lib/python3.10/site-packages/babel/locale-data/chr_US.dat +0 -0
- lib/python3.10/site-packages/babel/locale-data/kok_Deva.dat +0 -0
- lib/python3.10/site-packages/babel/locale-data/nr.dat +0 -0
- lib/python3.10/site-packages/babel/localedata.py +278 -0
- lib/python3.10/site-packages/babel/numbers.py +1590 -0
- lib/python3.10/site-packages/babel/plural.py +637 -0
- lib/python3.10/site-packages/babel/py.typed +1 -0
- lib/python3.10/site-packages/babel/support.py +726 -0
- lib/python3.10/site-packages/babel/units.py +340 -0
- lib/python3.10/site-packages/babel/util.py +296 -0
- lib/python3.10/site-packages/colorama/__init__.py +7 -0
- lib/python3.10/site-packages/colorama/ansi.py +102 -0
- lib/python3.10/site-packages/colorama/ansitowin32.py +277 -0
- lib/python3.10/site-packages/colorama/initialise.py +121 -0
- lib/python3.10/site-packages/colorama/win32.py +180 -0
- lib/python3.10/site-packages/colorama/winterm.py +195 -0
- lib/python3.10/site-packages/cryptography/hazmat/backends/__init__.py +13 -0
- lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/__init__.py +9 -0
- lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/backend.py +285 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/__init__.py +3 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi +28 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi +8 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi +7 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi +17 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi +117 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi +72 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi +103 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi +38 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi +18 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi +51 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi +41 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi +52 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi +12 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi +12 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi +19 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi +21 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi +43 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi +33 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi +13 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi +55 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi +12 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi +12 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi +46 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi +49 -0
- lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi +22 -0
lib/python3.10/site-packages/babel/__init__.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
babel
|
3 |
+
~~~~~
|
4 |
+
|
5 |
+
Integrated collection of utilities that assist in internationalizing and
|
6 |
+
localizing applications.
|
7 |
+
|
8 |
+
This package is basically composed of two major parts:
|
9 |
+
|
10 |
+
* tools to build and work with ``gettext`` message catalogs
|
11 |
+
* a Python interface to the CLDR (Common Locale Data Repository), providing
|
12 |
+
access to various locale display names, localized number and date
|
13 |
+
formatting, etc.
|
14 |
+
|
15 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
16 |
+
:license: BSD, see LICENSE for more details.
|
17 |
+
"""
|
18 |
+
|
19 |
+
from babel.core import (
|
20 |
+
Locale,
|
21 |
+
UnknownLocaleError,
|
22 |
+
default_locale,
|
23 |
+
get_locale_identifier,
|
24 |
+
negotiate_locale,
|
25 |
+
parse_locale,
|
26 |
+
)
|
27 |
+
|
28 |
+
__version__ = '2.17.0'
|
29 |
+
|
30 |
+
__all__ = [
|
31 |
+
'Locale',
|
32 |
+
'UnknownLocaleError',
|
33 |
+
'__version__',
|
34 |
+
'default_locale',
|
35 |
+
'get_locale_identifier',
|
36 |
+
'negotiate_locale',
|
37 |
+
'parse_locale',
|
38 |
+
]
|
lib/python3.10/site-packages/babel/core.py
ADDED
@@ -0,0 +1,1337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
babel.core
|
3 |
+
~~~~~~~~~~
|
4 |
+
|
5 |
+
Core locale representation and locale data access.
|
6 |
+
|
7 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
8 |
+
:license: BSD, see LICENSE for more details.
|
9 |
+
"""
|
10 |
+
|
11 |
+
from __future__ import annotations
|
12 |
+
|
13 |
+
import os
|
14 |
+
import pickle
|
15 |
+
from collections.abc import Iterable, Mapping
|
16 |
+
from typing import TYPE_CHECKING, Any, Literal
|
17 |
+
|
18 |
+
from babel import localedata
|
19 |
+
from babel.plural import PluralRule
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
'Locale',
|
23 |
+
'UnknownLocaleError',
|
24 |
+
'default_locale',
|
25 |
+
'get_global',
|
26 |
+
'get_locale_identifier',
|
27 |
+
'negotiate_locale',
|
28 |
+
'parse_locale',
|
29 |
+
]
|
30 |
+
|
31 |
+
if TYPE_CHECKING:
|
32 |
+
from typing_extensions import TypeAlias
|
33 |
+
|
34 |
+
_GLOBAL_KEY: TypeAlias = Literal[
|
35 |
+
"all_currencies",
|
36 |
+
"currency_fractions",
|
37 |
+
"language_aliases",
|
38 |
+
"likely_subtags",
|
39 |
+
"meta_zones",
|
40 |
+
"parent_exceptions",
|
41 |
+
"script_aliases",
|
42 |
+
"territory_aliases",
|
43 |
+
"territory_currencies",
|
44 |
+
"territory_languages",
|
45 |
+
"territory_zones",
|
46 |
+
"variant_aliases",
|
47 |
+
"windows_zone_mapping",
|
48 |
+
"zone_aliases",
|
49 |
+
"zone_territories",
|
50 |
+
]
|
51 |
+
|
52 |
+
_global_data: Mapping[_GLOBAL_KEY, Mapping[str, Any]] | None
|
53 |
+
|
54 |
+
_global_data = None
|
55 |
+
_default_plural_rule = PluralRule({})
|
56 |
+
|
57 |
+
|
58 |
+
def _raise_no_data_error():
|
59 |
+
raise RuntimeError('The babel data files are not available. '
|
60 |
+
'This usually happens because you are using '
|
61 |
+
'a source checkout from Babel and you did '
|
62 |
+
'not build the data files. Just make sure '
|
63 |
+
'to run "python setup.py import_cldr" before '
|
64 |
+
'installing the library.')
|
65 |
+
|
66 |
+
|
67 |
+
def get_global(key: _GLOBAL_KEY) -> Mapping[str, Any]:
|
68 |
+
"""Return the dictionary for the given key in the global data.
|
69 |
+
|
70 |
+
The global data is stored in the ``babel/global.dat`` file and contains
|
71 |
+
information independent of individual locales.
|
72 |
+
|
73 |
+
>>> get_global('zone_aliases')['UTC']
|
74 |
+
u'Etc/UTC'
|
75 |
+
>>> get_global('zone_territories')['Europe/Berlin']
|
76 |
+
u'DE'
|
77 |
+
|
78 |
+
The keys available are:
|
79 |
+
|
80 |
+
- ``all_currencies``
|
81 |
+
- ``currency_fractions``
|
82 |
+
- ``language_aliases``
|
83 |
+
- ``likely_subtags``
|
84 |
+
- ``parent_exceptions``
|
85 |
+
- ``script_aliases``
|
86 |
+
- ``territory_aliases``
|
87 |
+
- ``territory_currencies``
|
88 |
+
- ``territory_languages``
|
89 |
+
- ``territory_zones``
|
90 |
+
- ``variant_aliases``
|
91 |
+
- ``windows_zone_mapping``
|
92 |
+
- ``zone_aliases``
|
93 |
+
- ``zone_territories``
|
94 |
+
|
95 |
+
.. note:: The internal structure of the data may change between versions.
|
96 |
+
|
97 |
+
.. versionadded:: 0.9
|
98 |
+
|
99 |
+
:param key: the data key
|
100 |
+
"""
|
101 |
+
global _global_data
|
102 |
+
if _global_data is None:
|
103 |
+
dirname = os.path.join(os.path.dirname(__file__))
|
104 |
+
filename = os.path.join(dirname, 'global.dat')
|
105 |
+
if not os.path.isfile(filename):
|
106 |
+
_raise_no_data_error()
|
107 |
+
with open(filename, 'rb') as fileobj:
|
108 |
+
_global_data = pickle.load(fileobj)
|
109 |
+
assert _global_data is not None
|
110 |
+
return _global_data.get(key, {})
|
111 |
+
|
112 |
+
|
113 |
+
LOCALE_ALIASES = {
|
114 |
+
'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ',
|
115 |
+
'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES',
|
116 |
+
'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES',
|
117 |
+
'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it': 'it_IT',
|
118 |
+
'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV',
|
119 |
+
'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL',
|
120 |
+
'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI',
|
121 |
+
'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA',
|
122 |
+
}
|
123 |
+
|
124 |
+
|
125 |
+
class UnknownLocaleError(Exception):
|
126 |
+
"""Exception thrown when a locale is requested for which no locale data
|
127 |
+
is available.
|
128 |
+
"""
|
129 |
+
|
130 |
+
def __init__(self, identifier: str) -> None:
|
131 |
+
"""Create the exception.
|
132 |
+
|
133 |
+
:param identifier: the identifier string of the unsupported locale
|
134 |
+
"""
|
135 |
+
Exception.__init__(self, f"unknown locale {identifier!r}")
|
136 |
+
|
137 |
+
#: The identifier of the locale that could not be found.
|
138 |
+
self.identifier = identifier
|
139 |
+
|
140 |
+
|
141 |
+
class Locale:
|
142 |
+
"""Representation of a specific locale.
|
143 |
+
|
144 |
+
>>> locale = Locale('en', 'US')
|
145 |
+
>>> repr(locale)
|
146 |
+
"Locale('en', territory='US')"
|
147 |
+
>>> locale.display_name
|
148 |
+
u'English (United States)'
|
149 |
+
|
150 |
+
A `Locale` object can also be instantiated from a raw locale string:
|
151 |
+
|
152 |
+
>>> locale = Locale.parse('en-US', sep='-')
|
153 |
+
>>> repr(locale)
|
154 |
+
"Locale('en', territory='US')"
|
155 |
+
|
156 |
+
`Locale` objects provide access to a collection of locale data, such as
|
157 |
+
territory and language names, number and date format patterns, and more:
|
158 |
+
|
159 |
+
>>> locale.number_symbols['latn']['decimal']
|
160 |
+
u'.'
|
161 |
+
|
162 |
+
If a locale is requested for which no locale data is available, an
|
163 |
+
`UnknownLocaleError` is raised:
|
164 |
+
|
165 |
+
>>> Locale.parse('en_XX')
|
166 |
+
Traceback (most recent call last):
|
167 |
+
...
|
168 |
+
UnknownLocaleError: unknown locale 'en_XX'
|
169 |
+
|
170 |
+
For more information see :rfc:`3066`.
|
171 |
+
"""
|
172 |
+
|
173 |
+
def __init__(
|
174 |
+
self,
|
175 |
+
language: str,
|
176 |
+
territory: str | None = None,
|
177 |
+
script: str | None = None,
|
178 |
+
variant: str | None = None,
|
179 |
+
modifier: str | None = None,
|
180 |
+
) -> None:
|
181 |
+
"""Initialize the locale object from the given identifier components.
|
182 |
+
|
183 |
+
>>> locale = Locale('en', 'US')
|
184 |
+
>>> locale.language
|
185 |
+
'en'
|
186 |
+
>>> locale.territory
|
187 |
+
'US'
|
188 |
+
|
189 |
+
:param language: the language code
|
190 |
+
:param territory: the territory (country or region) code
|
191 |
+
:param script: the script code
|
192 |
+
:param variant: the variant code
|
193 |
+
:param modifier: a modifier (following the '@' symbol, sometimes called '@variant')
|
194 |
+
:raise `UnknownLocaleError`: if no locale data is available for the
|
195 |
+
requested locale
|
196 |
+
"""
|
197 |
+
#: the language code
|
198 |
+
self.language = language
|
199 |
+
#: the territory (country or region) code
|
200 |
+
self.territory = territory
|
201 |
+
#: the script code
|
202 |
+
self.script = script
|
203 |
+
#: the variant code
|
204 |
+
self.variant = variant
|
205 |
+
#: the modifier
|
206 |
+
self.modifier = modifier
|
207 |
+
self.__data: localedata.LocaleDataDict | None = None
|
208 |
+
|
209 |
+
identifier = str(self)
|
210 |
+
identifier_without_modifier = identifier.partition('@')[0]
|
211 |
+
if localedata.exists(identifier):
|
212 |
+
self.__data_identifier = identifier
|
213 |
+
elif localedata.exists(identifier_without_modifier):
|
214 |
+
self.__data_identifier = identifier_without_modifier
|
215 |
+
else:
|
216 |
+
raise UnknownLocaleError(identifier)
|
217 |
+
|
218 |
+
@classmethod
|
219 |
+
def default(cls, category: str | None = None, aliases: Mapping[str, str] = LOCALE_ALIASES) -> Locale:
|
220 |
+
"""Return the system default locale for the specified category.
|
221 |
+
|
222 |
+
>>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']:
|
223 |
+
... os.environ[name] = ''
|
224 |
+
>>> os.environ['LANG'] = 'fr_FR.UTF-8'
|
225 |
+
>>> Locale.default('LC_MESSAGES')
|
226 |
+
Locale('fr', territory='FR')
|
227 |
+
|
228 |
+
The following fallbacks to the variable are always considered:
|
229 |
+
|
230 |
+
- ``LANGUAGE``
|
231 |
+
- ``LC_ALL``
|
232 |
+
- ``LC_CTYPE``
|
233 |
+
- ``LANG``
|
234 |
+
|
235 |
+
:param category: one of the ``LC_XXX`` environment variable names
|
236 |
+
:param aliases: a dictionary of aliases for locale identifiers
|
237 |
+
"""
|
238 |
+
# XXX: use likely subtag expansion here instead of the
|
239 |
+
# aliases dictionary.
|
240 |
+
locale_string = default_locale(category, aliases=aliases)
|
241 |
+
return cls.parse(locale_string)
|
242 |
+
|
243 |
+
@classmethod
|
244 |
+
def negotiate(
|
245 |
+
cls,
|
246 |
+
preferred: Iterable[str],
|
247 |
+
available: Iterable[str],
|
248 |
+
sep: str = '_',
|
249 |
+
aliases: Mapping[str, str] = LOCALE_ALIASES,
|
250 |
+
) -> Locale | None:
|
251 |
+
"""Find the best match between available and requested locale strings.
|
252 |
+
|
253 |
+
>>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
|
254 |
+
Locale('de', territory='DE')
|
255 |
+
>>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
|
256 |
+
Locale('de')
|
257 |
+
>>> Locale.negotiate(['de_DE', 'de'], ['en_US'])
|
258 |
+
|
259 |
+
You can specify the character used in the locale identifiers to separate
|
260 |
+
the different components. This separator is applied to both lists. Also,
|
261 |
+
case is ignored in the comparison:
|
262 |
+
|
263 |
+
>>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
|
264 |
+
Locale('de', territory='DE')
|
265 |
+
|
266 |
+
:param preferred: the list of locale identifiers preferred by the user
|
267 |
+
:param available: the list of locale identifiers available
|
268 |
+
:param aliases: a dictionary of aliases for locale identifiers
|
269 |
+
:param sep: separator for parsing; e.g. Windows tends to use '-' instead of '_'.
|
270 |
+
"""
|
271 |
+
identifier = negotiate_locale(preferred, available, sep=sep,
|
272 |
+
aliases=aliases)
|
273 |
+
if identifier:
|
274 |
+
return Locale.parse(identifier, sep=sep)
|
275 |
+
return None
|
276 |
+
|
277 |
+
@classmethod
|
278 |
+
def parse(
|
279 |
+
cls,
|
280 |
+
identifier: Locale | str | None,
|
281 |
+
sep: str = '_',
|
282 |
+
resolve_likely_subtags: bool = True,
|
283 |
+
) -> Locale:
|
284 |
+
"""Create a `Locale` instance for the given locale identifier.
|
285 |
+
|
286 |
+
>>> l = Locale.parse('de-DE', sep='-')
|
287 |
+
>>> l.display_name
|
288 |
+
u'Deutsch (Deutschland)'
|
289 |
+
|
290 |
+
If the `identifier` parameter is not a string, but actually a `Locale`
|
291 |
+
object, that object is returned:
|
292 |
+
|
293 |
+
>>> Locale.parse(l)
|
294 |
+
Locale('de', territory='DE')
|
295 |
+
|
296 |
+
If the `identifier` parameter is neither of these, such as `None`
|
297 |
+
or an empty string, e.g. because a default locale identifier
|
298 |
+
could not be determined, a `TypeError` is raised:
|
299 |
+
|
300 |
+
>>> Locale.parse(None)
|
301 |
+
Traceback (most recent call last):
|
302 |
+
...
|
303 |
+
TypeError: ...
|
304 |
+
|
305 |
+
This also can perform resolving of likely subtags which it does
|
306 |
+
by default. This is for instance useful to figure out the most
|
307 |
+
likely locale for a territory you can use ``'und'`` as the
|
308 |
+
language tag:
|
309 |
+
|
310 |
+
>>> Locale.parse('und_AT')
|
311 |
+
Locale('de', territory='AT')
|
312 |
+
|
313 |
+
Modifiers are optional, and always at the end, separated by "@":
|
314 |
+
|
315 |
+
>>> Locale.parse('de_AT@euro')
|
316 |
+
Locale('de', territory='AT', modifier='euro')
|
317 |
+
|
318 |
+
:param identifier: the locale identifier string
|
319 |
+
:param sep: optional component separator
|
320 |
+
:param resolve_likely_subtags: if this is specified then a locale will
|
321 |
+
have its likely subtag resolved if the
|
322 |
+
locale otherwise does not exist. For
|
323 |
+
instance ``zh_TW`` by itself is not a
|
324 |
+
locale that exists but Babel can
|
325 |
+
automatically expand it to the full
|
326 |
+
form of ``zh_hant_TW``. Note that this
|
327 |
+
expansion is only taking place if no
|
328 |
+
locale exists otherwise. For instance
|
329 |
+
there is a locale ``en`` that can exist
|
330 |
+
by itself.
|
331 |
+
:raise `ValueError`: if the string does not appear to be a valid locale
|
332 |
+
identifier
|
333 |
+
:raise `UnknownLocaleError`: if no locale data is available for the
|
334 |
+
requested locale
|
335 |
+
:raise `TypeError`: if the identifier is not a string or a `Locale`
|
336 |
+
:raise `ValueError`: if the identifier is not a valid string
|
337 |
+
"""
|
338 |
+
if isinstance(identifier, Locale):
|
339 |
+
return identifier
|
340 |
+
|
341 |
+
if not identifier:
|
342 |
+
msg = (
|
343 |
+
f"Empty locale identifier value: {identifier!r}\n\n"
|
344 |
+
f"If you didn't explicitly pass an empty value to a Babel function, "
|
345 |
+
f"this could be caused by there being no suitable locale environment "
|
346 |
+
f"variables for the API you tried to use.",
|
347 |
+
)
|
348 |
+
if isinstance(identifier, str):
|
349 |
+
raise ValueError(msg) # `parse_locale` would raise a ValueError, so let's do that here
|
350 |
+
raise TypeError(msg)
|
351 |
+
|
352 |
+
if not isinstance(identifier, str):
|
353 |
+
raise TypeError(f"Unexpected value for identifier: {identifier!r}")
|
354 |
+
|
355 |
+
parts = parse_locale(identifier, sep=sep)
|
356 |
+
input_id = get_locale_identifier(parts)
|
357 |
+
|
358 |
+
def _try_load(parts):
|
359 |
+
try:
|
360 |
+
return cls(*parts)
|
361 |
+
except UnknownLocaleError:
|
362 |
+
return None
|
363 |
+
|
364 |
+
def _try_load_reducing(parts):
|
365 |
+
# Success on first hit, return it.
|
366 |
+
locale = _try_load(parts)
|
367 |
+
if locale is not None:
|
368 |
+
return locale
|
369 |
+
|
370 |
+
# Now try without script and variant
|
371 |
+
locale = _try_load(parts[:2])
|
372 |
+
if locale is not None:
|
373 |
+
return locale
|
374 |
+
|
375 |
+
locale = _try_load(parts)
|
376 |
+
if locale is not None:
|
377 |
+
return locale
|
378 |
+
if not resolve_likely_subtags:
|
379 |
+
raise UnknownLocaleError(input_id)
|
380 |
+
|
381 |
+
# From here onwards is some very bad likely subtag resolving. This
|
382 |
+
# whole logic is not entirely correct but good enough (tm) for the
|
383 |
+
# time being. This has been added so that zh_TW does not cause
|
384 |
+
# errors for people when they upgrade. Later we should properly
|
385 |
+
# implement ICU like fuzzy locale objects and provide a way to
|
386 |
+
# maximize and minimize locale tags.
|
387 |
+
|
388 |
+
if len(parts) == 5:
|
389 |
+
language, territory, script, variant, modifier = parts
|
390 |
+
else:
|
391 |
+
language, territory, script, variant = parts
|
392 |
+
modifier = None
|
393 |
+
language = get_global('language_aliases').get(language, language)
|
394 |
+
territory = get_global('territory_aliases').get(territory or '', (territory,))[0]
|
395 |
+
script = get_global('script_aliases').get(script or '', script)
|
396 |
+
variant = get_global('variant_aliases').get(variant or '', variant)
|
397 |
+
|
398 |
+
if territory == 'ZZ':
|
399 |
+
territory = None
|
400 |
+
if script == 'Zzzz':
|
401 |
+
script = None
|
402 |
+
|
403 |
+
parts = language, territory, script, variant, modifier
|
404 |
+
|
405 |
+
# First match: try the whole identifier
|
406 |
+
new_id = get_locale_identifier(parts)
|
407 |
+
likely_subtag = get_global('likely_subtags').get(new_id)
|
408 |
+
if likely_subtag is not None:
|
409 |
+
locale = _try_load_reducing(parse_locale(likely_subtag))
|
410 |
+
if locale is not None:
|
411 |
+
return locale
|
412 |
+
|
413 |
+
# If we did not find anything so far, try again with a
|
414 |
+
# simplified identifier that is just the language
|
415 |
+
likely_subtag = get_global('likely_subtags').get(language)
|
416 |
+
if likely_subtag is not None:
|
417 |
+
parts2 = parse_locale(likely_subtag)
|
418 |
+
if len(parts2) == 5:
|
419 |
+
language2, _, script2, variant2, modifier2 = parts2
|
420 |
+
else:
|
421 |
+
language2, _, script2, variant2 = parts2
|
422 |
+
modifier2 = None
|
423 |
+
locale = _try_load_reducing((language2, territory, script2, variant2, modifier2))
|
424 |
+
if locale is not None:
|
425 |
+
return locale
|
426 |
+
|
427 |
+
raise UnknownLocaleError(input_id)
|
428 |
+
|
429 |
+
def __eq__(self, other: object) -> bool:
|
430 |
+
for key in ('language', 'territory', 'script', 'variant', 'modifier'):
|
431 |
+
if not hasattr(other, key):
|
432 |
+
return False
|
433 |
+
return (
|
434 |
+
self.language == getattr(other, 'language') and # noqa: B009
|
435 |
+
self.territory == getattr(other, 'territory') and # noqa: B009
|
436 |
+
self.script == getattr(other, 'script') and # noqa: B009
|
437 |
+
self.variant == getattr(other, 'variant') and # noqa: B009
|
438 |
+
self.modifier == getattr(other, 'modifier') # noqa: B009
|
439 |
+
)
|
440 |
+
|
441 |
+
def __ne__(self, other: object) -> bool:
|
442 |
+
return not self.__eq__(other)
|
443 |
+
|
444 |
+
def __hash__(self) -> int:
|
445 |
+
return hash((self.language, self.territory, self.script,
|
446 |
+
self.variant, self.modifier))
|
447 |
+
|
448 |
+
def __repr__(self) -> str:
|
449 |
+
parameters = ['']
|
450 |
+
for key in ('territory', 'script', 'variant', 'modifier'):
|
451 |
+
value = getattr(self, key)
|
452 |
+
if value is not None:
|
453 |
+
parameters.append(f"{key}={value!r}")
|
454 |
+
return f"Locale({self.language!r}{', '.join(parameters)})"
|
455 |
+
|
456 |
+
def __str__(self) -> str:
|
457 |
+
return get_locale_identifier((self.language, self.territory,
|
458 |
+
self.script, self.variant,
|
459 |
+
self.modifier))
|
460 |
+
|
461 |
+
@property
|
462 |
+
def _data(self) -> localedata.LocaleDataDict:
|
463 |
+
if self.__data is None:
|
464 |
+
self.__data = localedata.LocaleDataDict(localedata.load(self.__data_identifier))
|
465 |
+
return self.__data
|
466 |
+
|
467 |
+
def get_display_name(self, locale: Locale | str | None = None) -> str | None:
|
468 |
+
"""Return the display name of the locale using the given locale.
|
469 |
+
|
470 |
+
The display name will include the language, territory, script, and
|
471 |
+
variant, if those are specified.
|
472 |
+
|
473 |
+
>>> Locale('zh', 'CN', script='Hans').get_display_name('en')
|
474 |
+
u'Chinese (Simplified, China)'
|
475 |
+
|
476 |
+
Modifiers are currently passed through verbatim:
|
477 |
+
|
478 |
+
>>> Locale('it', 'IT', modifier='euro').get_display_name('en')
|
479 |
+
u'Italian (Italy, euro)'
|
480 |
+
|
481 |
+
:param locale: the locale to use
|
482 |
+
"""
|
483 |
+
if locale is None:
|
484 |
+
locale = self
|
485 |
+
locale = Locale.parse(locale)
|
486 |
+
retval = locale.languages.get(self.language)
|
487 |
+
if retval and (self.territory or self.script or self.variant):
|
488 |
+
details = []
|
489 |
+
if self.script:
|
490 |
+
details.append(locale.scripts.get(self.script))
|
491 |
+
if self.territory:
|
492 |
+
details.append(locale.territories.get(self.territory))
|
493 |
+
if self.variant:
|
494 |
+
details.append(locale.variants.get(self.variant))
|
495 |
+
if self.modifier:
|
496 |
+
details.append(self.modifier)
|
497 |
+
detail_string = ', '.join(atom for atom in details if atom)
|
498 |
+
if detail_string:
|
499 |
+
retval += f" ({detail_string})"
|
500 |
+
return retval
|
501 |
+
|
502 |
+
display_name = property(get_display_name, doc="""\
|
503 |
+
The localized display name of the locale.
|
504 |
+
|
505 |
+
>>> Locale('en').display_name
|
506 |
+
u'English'
|
507 |
+
>>> Locale('en', 'US').display_name
|
508 |
+
u'English (United States)'
|
509 |
+
>>> Locale('sv').display_name
|
510 |
+
u'svenska'
|
511 |
+
|
512 |
+
:type: `unicode`
|
513 |
+
""")
|
514 |
+
|
515 |
+
def get_language_name(self, locale: Locale | str | None = None) -> str | None:
|
516 |
+
"""Return the language of this locale in the given locale.
|
517 |
+
|
518 |
+
>>> Locale('zh', 'CN', script='Hans').get_language_name('de')
|
519 |
+
u'Chinesisch'
|
520 |
+
|
521 |
+
.. versionadded:: 1.0
|
522 |
+
|
523 |
+
:param locale: the locale to use
|
524 |
+
"""
|
525 |
+
if locale is None:
|
526 |
+
locale = self
|
527 |
+
locale = Locale.parse(locale)
|
528 |
+
return locale.languages.get(self.language)
|
529 |
+
|
530 |
+
language_name = property(get_language_name, doc="""\
|
531 |
+
The localized language name of the locale.
|
532 |
+
|
533 |
+
>>> Locale('en', 'US').language_name
|
534 |
+
u'English'
|
535 |
+
""")
|
536 |
+
|
537 |
+
def get_territory_name(self, locale: Locale | str | None = None) -> str | None:
|
538 |
+
"""Return the territory name in the given locale."""
|
539 |
+
if locale is None:
|
540 |
+
locale = self
|
541 |
+
locale = Locale.parse(locale)
|
542 |
+
return locale.territories.get(self.territory or '')
|
543 |
+
|
544 |
+
territory_name = property(get_territory_name, doc="""\
|
545 |
+
The localized territory name of the locale if available.
|
546 |
+
|
547 |
+
>>> Locale('de', 'DE').territory_name
|
548 |
+
u'Deutschland'
|
549 |
+
""")
|
550 |
+
|
551 |
+
def get_script_name(self, locale: Locale | str | None = None) -> str | None:
|
552 |
+
"""Return the script name in the given locale."""
|
553 |
+
if locale is None:
|
554 |
+
locale = self
|
555 |
+
locale = Locale.parse(locale)
|
556 |
+
return locale.scripts.get(self.script or '')
|
557 |
+
|
558 |
+
script_name = property(get_script_name, doc="""\
|
559 |
+
The localized script name of the locale if available.
|
560 |
+
|
561 |
+
>>> Locale('sr', 'ME', script='Latn').script_name
|
562 |
+
u'latinica'
|
563 |
+
""")
|
564 |
+
|
565 |
+
@property
|
566 |
+
def english_name(self) -> str | None:
|
567 |
+
"""The english display name of the locale.
|
568 |
+
|
569 |
+
>>> Locale('de').english_name
|
570 |
+
u'German'
|
571 |
+
>>> Locale('de', 'DE').english_name
|
572 |
+
u'German (Germany)'
|
573 |
+
|
574 |
+
:type: `unicode`"""
|
575 |
+
return self.get_display_name(Locale('en'))
|
576 |
+
|
577 |
+
# { General Locale Display Names
|
578 |
+
|
579 |
+
@property
|
580 |
+
def languages(self) -> localedata.LocaleDataDict:
|
581 |
+
"""Mapping of language codes to translated language names.
|
582 |
+
|
583 |
+
>>> Locale('de', 'DE').languages['ja']
|
584 |
+
u'Japanisch'
|
585 |
+
|
586 |
+
See `ISO 639 <https://www.loc.gov/standards/iso639-2/>`_ for
|
587 |
+
more information.
|
588 |
+
"""
|
589 |
+
return self._data['languages']
|
590 |
+
|
591 |
+
@property
|
592 |
+
def scripts(self) -> localedata.LocaleDataDict:
|
593 |
+
"""Mapping of script codes to translated script names.
|
594 |
+
|
595 |
+
>>> Locale('en', 'US').scripts['Hira']
|
596 |
+
u'Hiragana'
|
597 |
+
|
598 |
+
See `ISO 15924 <https://www.unicode.org/iso15924/>`_
|
599 |
+
for more information.
|
600 |
+
"""
|
601 |
+
return self._data['scripts']
|
602 |
+
|
603 |
+
@property
|
604 |
+
def territories(self) -> localedata.LocaleDataDict:
|
605 |
+
"""Mapping of script codes to translated script names.
|
606 |
+
|
607 |
+
>>> Locale('es', 'CO').territories['DE']
|
608 |
+
u'Alemania'
|
609 |
+
|
610 |
+
See `ISO 3166 <https://en.wikipedia.org/wiki/ISO_3166>`_
|
611 |
+
for more information.
|
612 |
+
"""
|
613 |
+
return self._data['territories']
|
614 |
+
|
615 |
+
@property
|
616 |
+
def variants(self) -> localedata.LocaleDataDict:
|
617 |
+
"""Mapping of script codes to translated script names.
|
618 |
+
|
619 |
+
>>> Locale('de', 'DE').variants['1901']
|
620 |
+
u'Alte deutsche Rechtschreibung'
|
621 |
+
"""
|
622 |
+
return self._data['variants']
|
623 |
+
|
624 |
+
# { Number Formatting
|
625 |
+
|
626 |
+
@property
|
627 |
+
def currencies(self) -> localedata.LocaleDataDict:
|
628 |
+
"""Mapping of currency codes to translated currency names. This
|
629 |
+
only returns the generic form of the currency name, not the count
|
630 |
+
specific one. If an actual number is requested use the
|
631 |
+
:func:`babel.numbers.get_currency_name` function.
|
632 |
+
|
633 |
+
>>> Locale('en').currencies['COP']
|
634 |
+
u'Colombian Peso'
|
635 |
+
>>> Locale('de', 'DE').currencies['COP']
|
636 |
+
u'Kolumbianischer Peso'
|
637 |
+
"""
|
638 |
+
return self._data['currency_names']
|
639 |
+
|
640 |
+
@property
|
641 |
+
def currency_symbols(self) -> localedata.LocaleDataDict:
|
642 |
+
"""Mapping of currency codes to symbols.
|
643 |
+
|
644 |
+
>>> Locale('en', 'US').currency_symbols['USD']
|
645 |
+
u'$'
|
646 |
+
>>> Locale('es', 'CO').currency_symbols['USD']
|
647 |
+
u'US$'
|
648 |
+
"""
|
649 |
+
return self._data['currency_symbols']
|
650 |
+
|
651 |
+
@property
|
652 |
+
def number_symbols(self) -> localedata.LocaleDataDict:
|
653 |
+
"""Symbols used in number formatting by number system.
|
654 |
+
|
655 |
+
.. note:: The format of the value returned may change between
|
656 |
+
Babel versions.
|
657 |
+
|
658 |
+
>>> Locale('fr', 'FR').number_symbols["latn"]['decimal']
|
659 |
+
u','
|
660 |
+
>>> Locale('fa', 'IR').number_symbols["arabext"]['decimal']
|
661 |
+
u'٫'
|
662 |
+
>>> Locale('fa', 'IR').number_symbols["latn"]['decimal']
|
663 |
+
u'.'
|
664 |
+
"""
|
665 |
+
return self._data['number_symbols']
|
666 |
+
|
667 |
+
@property
|
668 |
+
def other_numbering_systems(self) -> localedata.LocaleDataDict:
|
669 |
+
"""
|
670 |
+
Mapping of other numbering systems available for the locale.
|
671 |
+
See: https://www.unicode.org/reports/tr35/tr35-numbers.html#otherNumberingSystems
|
672 |
+
|
673 |
+
>>> Locale('el', 'GR').other_numbering_systems['traditional']
|
674 |
+
u'grek'
|
675 |
+
|
676 |
+
.. note:: The format of the value returned may change between
|
677 |
+
Babel versions.
|
678 |
+
"""
|
679 |
+
return self._data['numbering_systems']
|
680 |
+
|
681 |
+
@property
|
682 |
+
def default_numbering_system(self) -> str:
|
683 |
+
"""The default numbering system used by the locale.
|
684 |
+
>>> Locale('el', 'GR').default_numbering_system
|
685 |
+
u'latn'
|
686 |
+
"""
|
687 |
+
return self._data['default_numbering_system']
|
688 |
+
|
689 |
+
@property
|
690 |
+
def decimal_formats(self) -> localedata.LocaleDataDict:
|
691 |
+
"""Locale patterns for decimal number formatting.
|
692 |
+
|
693 |
+
.. note:: The format of the value returned may change between
|
694 |
+
Babel versions.
|
695 |
+
|
696 |
+
>>> Locale('en', 'US').decimal_formats[None]
|
697 |
+
<NumberPattern u'#,##0.###'>
|
698 |
+
"""
|
699 |
+
return self._data['decimal_formats']
|
700 |
+
|
701 |
+
@property
|
702 |
+
def compact_decimal_formats(self) -> localedata.LocaleDataDict:
|
703 |
+
"""Locale patterns for compact decimal number formatting.
|
704 |
+
|
705 |
+
.. note:: The format of the value returned may change between
|
706 |
+
Babel versions.
|
707 |
+
|
708 |
+
>>> Locale('en', 'US').compact_decimal_formats["short"]["one"]["1000"]
|
709 |
+
<NumberPattern u'0K'>
|
710 |
+
"""
|
711 |
+
return self._data['compact_decimal_formats']
|
712 |
+
|
713 |
+
@property
|
714 |
+
def currency_formats(self) -> localedata.LocaleDataDict:
|
715 |
+
"""Locale patterns for currency number formatting.
|
716 |
+
|
717 |
+
.. note:: The format of the value returned may change between
|
718 |
+
Babel versions.
|
719 |
+
|
720 |
+
>>> Locale('en', 'US').currency_formats['standard']
|
721 |
+
<NumberPattern u'\\xa4#,##0.00'>
|
722 |
+
>>> Locale('en', 'US').currency_formats['accounting']
|
723 |
+
<NumberPattern u'\\xa4#,##0.00;(\\xa4#,##0.00)'>
|
724 |
+
"""
|
725 |
+
return self._data['currency_formats']
|
726 |
+
|
727 |
+
@property
|
728 |
+
def compact_currency_formats(self) -> localedata.LocaleDataDict:
|
729 |
+
"""Locale patterns for compact currency number formatting.
|
730 |
+
|
731 |
+
.. note:: The format of the value returned may change between
|
732 |
+
Babel versions.
|
733 |
+
|
734 |
+
>>> Locale('en', 'US').compact_currency_formats["short"]["one"]["1000"]
|
735 |
+
<NumberPattern u'¤0K'>
|
736 |
+
"""
|
737 |
+
return self._data['compact_currency_formats']
|
738 |
+
|
739 |
+
@property
|
740 |
+
def percent_formats(self) -> localedata.LocaleDataDict:
|
741 |
+
"""Locale patterns for percent number formatting.
|
742 |
+
|
743 |
+
.. note:: The format of the value returned may change between
|
744 |
+
Babel versions.
|
745 |
+
|
746 |
+
>>> Locale('en', 'US').percent_formats[None]
|
747 |
+
<NumberPattern u'#,##0%'>
|
748 |
+
"""
|
749 |
+
return self._data['percent_formats']
|
750 |
+
|
751 |
+
@property
|
752 |
+
def scientific_formats(self) -> localedata.LocaleDataDict:
|
753 |
+
"""Locale patterns for scientific number formatting.
|
754 |
+
|
755 |
+
.. note:: The format of the value returned may change between
|
756 |
+
Babel versions.
|
757 |
+
|
758 |
+
>>> Locale('en', 'US').scientific_formats[None]
|
759 |
+
<NumberPattern u'#E0'>
|
760 |
+
"""
|
761 |
+
return self._data['scientific_formats']
|
762 |
+
|
763 |
+
# { Calendar Information and Date Formatting
|
764 |
+
|
765 |
+
@property
|
766 |
+
def periods(self) -> localedata.LocaleDataDict:
|
767 |
+
"""Locale display names for day periods (AM/PM).
|
768 |
+
|
769 |
+
>>> Locale('en', 'US').periods['am']
|
770 |
+
u'AM'
|
771 |
+
"""
|
772 |
+
try:
|
773 |
+
return self._data['day_periods']['stand-alone']['wide']
|
774 |
+
except KeyError:
|
775 |
+
return localedata.LocaleDataDict({}) # pragma: no cover
|
776 |
+
|
777 |
+
@property
|
778 |
+
def day_periods(self) -> localedata.LocaleDataDict:
|
779 |
+
"""Locale display names for various day periods (not necessarily only AM/PM).
|
780 |
+
|
781 |
+
These are not meant to be used without the relevant `day_period_rules`.
|
782 |
+
"""
|
783 |
+
return self._data['day_periods']
|
784 |
+
|
785 |
+
@property
|
786 |
+
def day_period_rules(self) -> localedata.LocaleDataDict:
|
787 |
+
"""Day period rules for the locale. Used by `get_period_id`.
|
788 |
+
"""
|
789 |
+
return self._data.get('day_period_rules', localedata.LocaleDataDict({}))
|
790 |
+
|
791 |
+
@property
|
792 |
+
def days(self) -> localedata.LocaleDataDict:
|
793 |
+
"""Locale display names for weekdays.
|
794 |
+
|
795 |
+
>>> Locale('de', 'DE').days['format']['wide'][3]
|
796 |
+
u'Donnerstag'
|
797 |
+
"""
|
798 |
+
return self._data['days']
|
799 |
+
|
800 |
+
@property
|
801 |
+
def months(self) -> localedata.LocaleDataDict:
|
802 |
+
"""Locale display names for months.
|
803 |
+
|
804 |
+
>>> Locale('de', 'DE').months['format']['wide'][10]
|
805 |
+
u'Oktober'
|
806 |
+
"""
|
807 |
+
return self._data['months']
|
808 |
+
|
809 |
+
@property
|
810 |
+
def quarters(self) -> localedata.LocaleDataDict:
|
811 |
+
"""Locale display names for quarters.
|
812 |
+
|
813 |
+
>>> Locale('de', 'DE').quarters['format']['wide'][1]
|
814 |
+
u'1. Quartal'
|
815 |
+
"""
|
816 |
+
return self._data['quarters']
|
817 |
+
|
818 |
+
@property
|
819 |
+
def eras(self) -> localedata.LocaleDataDict:
|
820 |
+
"""Locale display names for eras.
|
821 |
+
|
822 |
+
.. note:: The format of the value returned may change between
|
823 |
+
Babel versions.
|
824 |
+
|
825 |
+
>>> Locale('en', 'US').eras['wide'][1]
|
826 |
+
u'Anno Domini'
|
827 |
+
>>> Locale('en', 'US').eras['abbreviated'][0]
|
828 |
+
u'BC'
|
829 |
+
"""
|
830 |
+
return self._data['eras']
|
831 |
+
|
832 |
+
@property
|
833 |
+
def time_zones(self) -> localedata.LocaleDataDict:
|
834 |
+
"""Locale display names for time zones.
|
835 |
+
|
836 |
+
.. note:: The format of the value returned may change between
|
837 |
+
Babel versions.
|
838 |
+
|
839 |
+
>>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight']
|
840 |
+
u'British Summer Time'
|
841 |
+
>>> Locale('en', 'US').time_zones['America/St_Johns']['city']
|
842 |
+
u'St. John\u2019s'
|
843 |
+
"""
|
844 |
+
return self._data['time_zones']
|
845 |
+
|
846 |
+
@property
|
847 |
+
def meta_zones(self) -> localedata.LocaleDataDict:
|
848 |
+
"""Locale display names for meta time zones.
|
849 |
+
|
850 |
+
Meta time zones are basically groups of different Olson time zones that
|
851 |
+
have the same GMT offset and daylight savings time.
|
852 |
+
|
853 |
+
.. note:: The format of the value returned may change between
|
854 |
+
Babel versions.
|
855 |
+
|
856 |
+
>>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight']
|
857 |
+
u'Central European Summer Time'
|
858 |
+
|
859 |
+
.. versionadded:: 0.9
|
860 |
+
"""
|
861 |
+
return self._data['meta_zones']
|
862 |
+
|
863 |
+
@property
|
864 |
+
def zone_formats(self) -> localedata.LocaleDataDict:
|
865 |
+
"""Patterns related to the formatting of time zones.
|
866 |
+
|
867 |
+
.. note:: The format of the value returned may change between
|
868 |
+
Babel versions.
|
869 |
+
|
870 |
+
>>> Locale('en', 'US').zone_formats['fallback']
|
871 |
+
u'%(1)s (%(0)s)'
|
872 |
+
>>> Locale('pt', 'BR').zone_formats['region']
|
873 |
+
u'Hor\\xe1rio %s'
|
874 |
+
|
875 |
+
.. versionadded:: 0.9
|
876 |
+
"""
|
877 |
+
return self._data['zone_formats']
|
878 |
+
|
879 |
+
@property
|
880 |
+
def first_week_day(self) -> int:
|
881 |
+
"""The first day of a week, with 0 being Monday.
|
882 |
+
|
883 |
+
>>> Locale('de', 'DE').first_week_day
|
884 |
+
0
|
885 |
+
>>> Locale('en', 'US').first_week_day
|
886 |
+
6
|
887 |
+
"""
|
888 |
+
return self._data['week_data']['first_day']
|
889 |
+
|
890 |
+
@property
|
891 |
+
def weekend_start(self) -> int:
|
892 |
+
"""The day the weekend starts, with 0 being Monday.
|
893 |
+
|
894 |
+
>>> Locale('de', 'DE').weekend_start
|
895 |
+
5
|
896 |
+
"""
|
897 |
+
return self._data['week_data']['weekend_start']
|
898 |
+
|
899 |
+
@property
|
900 |
+
def weekend_end(self) -> int:
|
901 |
+
"""The day the weekend ends, with 0 being Monday.
|
902 |
+
|
903 |
+
>>> Locale('de', 'DE').weekend_end
|
904 |
+
6
|
905 |
+
"""
|
906 |
+
return self._data['week_data']['weekend_end']
|
907 |
+
|
908 |
+
@property
|
909 |
+
def min_week_days(self) -> int:
|
910 |
+
"""The minimum number of days in a week so that the week is counted as
|
911 |
+
the first week of a year or month.
|
912 |
+
|
913 |
+
>>> Locale('de', 'DE').min_week_days
|
914 |
+
4
|
915 |
+
"""
|
916 |
+
return self._data['week_data']['min_days']
|
917 |
+
|
918 |
+
@property
|
919 |
+
def date_formats(self) -> localedata.LocaleDataDict:
|
920 |
+
"""Locale patterns for date formatting.
|
921 |
+
|
922 |
+
.. note:: The format of the value returned may change between
|
923 |
+
Babel versions.
|
924 |
+
|
925 |
+
>>> Locale('en', 'US').date_formats['short']
|
926 |
+
<DateTimePattern u'M/d/yy'>
|
927 |
+
>>> Locale('fr', 'FR').date_formats['long']
|
928 |
+
<DateTimePattern u'd MMMM y'>
|
929 |
+
"""
|
930 |
+
return self._data['date_formats']
|
931 |
+
|
932 |
+
@property
|
933 |
+
def time_formats(self) -> localedata.LocaleDataDict:
|
934 |
+
"""Locale patterns for time formatting.
|
935 |
+
|
936 |
+
.. note:: The format of the value returned may change between
|
937 |
+
Babel versions.
|
938 |
+
|
939 |
+
>>> Locale('en', 'US').time_formats['short']
|
940 |
+
<DateTimePattern u'h:mm\u202fa'>
|
941 |
+
>>> Locale('fr', 'FR').time_formats['long']
|
942 |
+
<DateTimePattern u'HH:mm:ss z'>
|
943 |
+
"""
|
944 |
+
return self._data['time_formats']
|
945 |
+
|
946 |
+
@property
|
947 |
+
def datetime_formats(self) -> localedata.LocaleDataDict:
|
948 |
+
"""Locale patterns for datetime formatting.
|
949 |
+
|
950 |
+
.. note:: The format of the value returned may change between
|
951 |
+
Babel versions.
|
952 |
+
|
953 |
+
>>> Locale('en').datetime_formats['full']
|
954 |
+
u'{1}, {0}'
|
955 |
+
>>> Locale('th').datetime_formats['medium']
|
956 |
+
u'{1} {0}'
|
957 |
+
"""
|
958 |
+
return self._data['datetime_formats']
|
959 |
+
|
960 |
+
@property
|
961 |
+
def datetime_skeletons(self) -> localedata.LocaleDataDict:
|
962 |
+
"""Locale patterns for formatting parts of a datetime.
|
963 |
+
|
964 |
+
>>> Locale('en').datetime_skeletons['MEd']
|
965 |
+
<DateTimePattern u'E, M/d'>
|
966 |
+
>>> Locale('fr').datetime_skeletons['MEd']
|
967 |
+
<DateTimePattern u'E dd/MM'>
|
968 |
+
>>> Locale('fr').datetime_skeletons['H']
|
969 |
+
<DateTimePattern u"HH 'h'">
|
970 |
+
"""
|
971 |
+
return self._data['datetime_skeletons']
|
972 |
+
|
973 |
+
@property
|
974 |
+
def interval_formats(self) -> localedata.LocaleDataDict:
|
975 |
+
"""Locale patterns for interval formatting.
|
976 |
+
|
977 |
+
.. note:: The format of the value returned may change between
|
978 |
+
Babel versions.
|
979 |
+
|
980 |
+
How to format date intervals in Finnish when the day is the
|
981 |
+
smallest changing component:
|
982 |
+
|
983 |
+
>>> Locale('fi_FI').interval_formats['MEd']['d']
|
984 |
+
[u'E d.\u2009\u2013\u2009', u'E d.M.']
|
985 |
+
|
986 |
+
.. seealso::
|
987 |
+
|
988 |
+
The primary API to use this data is :py:func:`babel.dates.format_interval`.
|
989 |
+
|
990 |
+
|
991 |
+
:rtype: dict[str, dict[str, list[str]]]
|
992 |
+
"""
|
993 |
+
return self._data['interval_formats']
|
994 |
+
|
995 |
+
@property
|
996 |
+
def plural_form(self) -> PluralRule:
|
997 |
+
"""Plural rules for the locale.
|
998 |
+
|
999 |
+
>>> Locale('en').plural_form(1)
|
1000 |
+
'one'
|
1001 |
+
>>> Locale('en').plural_form(0)
|
1002 |
+
'other'
|
1003 |
+
>>> Locale('fr').plural_form(0)
|
1004 |
+
'one'
|
1005 |
+
>>> Locale('ru').plural_form(100)
|
1006 |
+
'many'
|
1007 |
+
"""
|
1008 |
+
return self._data.get('plural_form', _default_plural_rule)
|
1009 |
+
|
1010 |
+
@property
|
1011 |
+
def list_patterns(self) -> localedata.LocaleDataDict:
|
1012 |
+
"""Patterns for generating lists
|
1013 |
+
|
1014 |
+
.. note:: The format of the value returned may change between
|
1015 |
+
Babel versions.
|
1016 |
+
|
1017 |
+
>>> Locale('en').list_patterns['standard']['start']
|
1018 |
+
u'{0}, {1}'
|
1019 |
+
>>> Locale('en').list_patterns['standard']['end']
|
1020 |
+
u'{0}, and {1}'
|
1021 |
+
>>> Locale('en_GB').list_patterns['standard']['end']
|
1022 |
+
u'{0} and {1}'
|
1023 |
+
"""
|
1024 |
+
return self._data['list_patterns']
|
1025 |
+
|
1026 |
+
@property
|
1027 |
+
def ordinal_form(self) -> PluralRule:
|
1028 |
+
"""Plural rules for the locale.
|
1029 |
+
|
1030 |
+
>>> Locale('en').ordinal_form(1)
|
1031 |
+
'one'
|
1032 |
+
>>> Locale('en').ordinal_form(2)
|
1033 |
+
'two'
|
1034 |
+
>>> Locale('en').ordinal_form(3)
|
1035 |
+
'few'
|
1036 |
+
>>> Locale('fr').ordinal_form(2)
|
1037 |
+
'other'
|
1038 |
+
>>> Locale('ru').ordinal_form(100)
|
1039 |
+
'other'
|
1040 |
+
"""
|
1041 |
+
return self._data.get('ordinal_form', _default_plural_rule)
|
1042 |
+
|
1043 |
+
@property
|
1044 |
+
def measurement_systems(self) -> localedata.LocaleDataDict:
|
1045 |
+
"""Localized names for various measurement systems.
|
1046 |
+
|
1047 |
+
>>> Locale('fr', 'FR').measurement_systems['US']
|
1048 |
+
u'am\\xe9ricain'
|
1049 |
+
>>> Locale('en', 'US').measurement_systems['US']
|
1050 |
+
u'US'
|
1051 |
+
|
1052 |
+
"""
|
1053 |
+
return self._data['measurement_systems']
|
1054 |
+
|
1055 |
+
@property
|
1056 |
+
def character_order(self) -> str:
|
1057 |
+
"""The text direction for the language.
|
1058 |
+
|
1059 |
+
>>> Locale('de', 'DE').character_order
|
1060 |
+
'left-to-right'
|
1061 |
+
>>> Locale('ar', 'SA').character_order
|
1062 |
+
'right-to-left'
|
1063 |
+
"""
|
1064 |
+
return self._data['character_order']
|
1065 |
+
|
1066 |
+
@property
|
1067 |
+
def text_direction(self) -> str:
|
1068 |
+
"""The text direction for the language in CSS short-hand form.
|
1069 |
+
|
1070 |
+
>>> Locale('de', 'DE').text_direction
|
1071 |
+
'ltr'
|
1072 |
+
>>> Locale('ar', 'SA').text_direction
|
1073 |
+
'rtl'
|
1074 |
+
"""
|
1075 |
+
return ''.join(word[0] for word in self.character_order.split('-'))
|
1076 |
+
|
1077 |
+
@property
|
1078 |
+
def unit_display_names(self) -> localedata.LocaleDataDict:
|
1079 |
+
"""Display names for units of measurement.
|
1080 |
+
|
1081 |
+
.. seealso::
|
1082 |
+
|
1083 |
+
You may want to use :py:func:`babel.units.get_unit_name` instead.
|
1084 |
+
|
1085 |
+
.. note:: The format of the value returned may change between
|
1086 |
+
Babel versions.
|
1087 |
+
|
1088 |
+
"""
|
1089 |
+
return self._data['unit_display_names']
|
1090 |
+
|
1091 |
+
|
1092 |
+
def default_locale(
|
1093 |
+
category: str | tuple[str, ...] | list[str] | None = None,
|
1094 |
+
aliases: Mapping[str, str] = LOCALE_ALIASES,
|
1095 |
+
) -> str | None:
|
1096 |
+
"""Returns the system default locale for a given category, based on
|
1097 |
+
environment variables.
|
1098 |
+
|
1099 |
+
>>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
|
1100 |
+
... os.environ[name] = ''
|
1101 |
+
>>> os.environ['LANG'] = 'fr_FR.UTF-8'
|
1102 |
+
>>> default_locale('LC_MESSAGES')
|
1103 |
+
'fr_FR'
|
1104 |
+
|
1105 |
+
The "C" or "POSIX" pseudo-locales are treated as aliases for the
|
1106 |
+
"en_US_POSIX" locale:
|
1107 |
+
|
1108 |
+
>>> os.environ['LC_MESSAGES'] = 'POSIX'
|
1109 |
+
>>> default_locale('LC_MESSAGES')
|
1110 |
+
'en_US_POSIX'
|
1111 |
+
|
1112 |
+
The following fallbacks to the variable are always considered:
|
1113 |
+
|
1114 |
+
- ``LANGUAGE``
|
1115 |
+
- ``LC_ALL``
|
1116 |
+
- ``LC_CTYPE``
|
1117 |
+
- ``LANG``
|
1118 |
+
|
1119 |
+
:param category: one or more of the ``LC_XXX`` environment variable names
|
1120 |
+
:param aliases: a dictionary of aliases for locale identifiers
|
1121 |
+
"""
|
1122 |
+
|
1123 |
+
varnames = ('LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG')
|
1124 |
+
if category:
|
1125 |
+
if isinstance(category, str):
|
1126 |
+
varnames = (category, *varnames)
|
1127 |
+
elif isinstance(category, (list, tuple)):
|
1128 |
+
varnames = (*category, *varnames)
|
1129 |
+
else:
|
1130 |
+
raise TypeError(f"Invalid type for category: {category!r}")
|
1131 |
+
|
1132 |
+
for name in varnames:
|
1133 |
+
if not name:
|
1134 |
+
continue
|
1135 |
+
locale = os.getenv(name)
|
1136 |
+
if locale:
|
1137 |
+
if name == 'LANGUAGE' and ':' in locale:
|
1138 |
+
# the LANGUAGE variable may contain a colon-separated list of
|
1139 |
+
# language codes; we just pick the language on the list
|
1140 |
+
locale = locale.split(':')[0]
|
1141 |
+
if locale.split('.')[0] in ('C', 'POSIX'):
|
1142 |
+
locale = 'en_US_POSIX'
|
1143 |
+
elif aliases and locale in aliases:
|
1144 |
+
locale = aliases[locale]
|
1145 |
+
try:
|
1146 |
+
return get_locale_identifier(parse_locale(locale))
|
1147 |
+
except ValueError:
|
1148 |
+
pass
|
1149 |
+
return None
|
1150 |
+
|
1151 |
+
|
1152 |
+
def negotiate_locale(preferred: Iterable[str], available: Iterable[str], sep: str = '_', aliases: Mapping[str, str] = LOCALE_ALIASES) -> str | None:
|
1153 |
+
"""Find the best match between available and requested locale strings.
|
1154 |
+
|
1155 |
+
>>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
|
1156 |
+
'de_DE'
|
1157 |
+
>>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de'])
|
1158 |
+
'de'
|
1159 |
+
|
1160 |
+
Case is ignored by the algorithm, the result uses the case of the preferred
|
1161 |
+
locale identifier:
|
1162 |
+
|
1163 |
+
>>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
|
1164 |
+
'de_DE'
|
1165 |
+
|
1166 |
+
>>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
|
1167 |
+
'de_DE'
|
1168 |
+
|
1169 |
+
By default, some web browsers unfortunately do not include the territory
|
1170 |
+
in the locale identifier for many locales, and some don't even allow the
|
1171 |
+
user to easily add the territory. So while you may prefer using qualified
|
1172 |
+
locale identifiers in your web-application, they would not normally match
|
1173 |
+
the language-only locale sent by such browsers. To workaround that, this
|
1174 |
+
function uses a default mapping of commonly used language-only locale
|
1175 |
+
identifiers to identifiers including the territory:
|
1176 |
+
|
1177 |
+
>>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US'])
|
1178 |
+
'ja_JP'
|
1179 |
+
|
1180 |
+
Some browsers even use an incorrect or outdated language code, such as "no"
|
1181 |
+
for Norwegian, where the correct locale identifier would actually be "nb_NO"
|
1182 |
+
(Bokmål) or "nn_NO" (Nynorsk). The aliases are intended to take care of
|
1183 |
+
such cases, too:
|
1184 |
+
|
1185 |
+
>>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE'])
|
1186 |
+
'nb_NO'
|
1187 |
+
|
1188 |
+
You can override this default mapping by passing a different `aliases`
|
1189 |
+
dictionary to this function, or you can bypass the behavior althogher by
|
1190 |
+
setting the `aliases` parameter to `None`.
|
1191 |
+
|
1192 |
+
:param preferred: the list of locale strings preferred by the user
|
1193 |
+
:param available: the list of locale strings available
|
1194 |
+
:param sep: character that separates the different parts of the locale
|
1195 |
+
strings
|
1196 |
+
:param aliases: a dictionary of aliases for locale identifiers
|
1197 |
+
"""
|
1198 |
+
available = [a.lower() for a in available if a]
|
1199 |
+
for locale in preferred:
|
1200 |
+
ll = locale.lower()
|
1201 |
+
if ll in available:
|
1202 |
+
return locale
|
1203 |
+
if aliases:
|
1204 |
+
alias = aliases.get(ll)
|
1205 |
+
if alias:
|
1206 |
+
alias = alias.replace('_', sep)
|
1207 |
+
if alias.lower() in available:
|
1208 |
+
return alias
|
1209 |
+
parts = locale.split(sep)
|
1210 |
+
if len(parts) > 1 and parts[0].lower() in available:
|
1211 |
+
return parts[0]
|
1212 |
+
return None
|
1213 |
+
|
1214 |
+
|
1215 |
+
def parse_locale(
|
1216 |
+
identifier: str,
|
1217 |
+
sep: str = '_',
|
1218 |
+
) -> tuple[str, str | None, str | None, str | None] | tuple[str, str | None, str | None, str | None, str | None]:
|
1219 |
+
"""Parse a locale identifier into a tuple of the form ``(language,
|
1220 |
+
territory, script, variant, modifier)``.
|
1221 |
+
|
1222 |
+
>>> parse_locale('zh_CN')
|
1223 |
+
('zh', 'CN', None, None)
|
1224 |
+
>>> parse_locale('zh_Hans_CN')
|
1225 |
+
('zh', 'CN', 'Hans', None)
|
1226 |
+
>>> parse_locale('ca_es_valencia')
|
1227 |
+
('ca', 'ES', None, 'VALENCIA')
|
1228 |
+
>>> parse_locale('en_150')
|
1229 |
+
('en', '150', None, None)
|
1230 |
+
>>> parse_locale('en_us_posix')
|
1231 |
+
('en', 'US', None, 'POSIX')
|
1232 |
+
>>> parse_locale('it_IT@euro')
|
1233 |
+
('it', 'IT', None, None, 'euro')
|
1234 |
+
>>> parse_locale('it_IT@custom')
|
1235 |
+
('it', 'IT', None, None, 'custom')
|
1236 |
+
>>> parse_locale('it_IT@')
|
1237 |
+
('it', 'IT', None, None)
|
1238 |
+
|
1239 |
+
The default component separator is "_", but a different separator can be
|
1240 |
+
specified using the `sep` parameter.
|
1241 |
+
|
1242 |
+
The optional modifier is always separated with "@" and at the end:
|
1243 |
+
|
1244 |
+
>>> parse_locale('zh-CN', sep='-')
|
1245 |
+
('zh', 'CN', None, None)
|
1246 |
+
>>> parse_locale('zh-CN@custom', sep='-')
|
1247 |
+
('zh', 'CN', None, None, 'custom')
|
1248 |
+
|
1249 |
+
If the identifier cannot be parsed into a locale, a `ValueError` exception
|
1250 |
+
is raised:
|
1251 |
+
|
1252 |
+
>>> parse_locale('not_a_LOCALE_String')
|
1253 |
+
Traceback (most recent call last):
|
1254 |
+
...
|
1255 |
+
ValueError: 'not_a_LOCALE_String' is not a valid locale identifier
|
1256 |
+
|
1257 |
+
Encoding information is removed from the identifier, while modifiers are
|
1258 |
+
kept:
|
1259 |
+
|
1260 |
+
>>> parse_locale('en_US.UTF-8')
|
1261 |
+
('en', 'US', None, None)
|
1262 |
+
>>> parse_locale('de_DE.iso885915@euro')
|
1263 |
+
('de', 'DE', None, None, 'euro')
|
1264 |
+
|
1265 |
+
See :rfc:`4646` for more information.
|
1266 |
+
|
1267 |
+
:param identifier: the locale identifier string
|
1268 |
+
:param sep: character that separates the different components of the locale
|
1269 |
+
identifier
|
1270 |
+
:raise `ValueError`: if the string does not appear to be a valid locale
|
1271 |
+
identifier
|
1272 |
+
"""
|
1273 |
+
if not identifier:
|
1274 |
+
raise ValueError("empty locale identifier")
|
1275 |
+
identifier, _, modifier = identifier.partition('@')
|
1276 |
+
if '.' in identifier:
|
1277 |
+
# this is probably the charset/encoding, which we don't care about
|
1278 |
+
identifier = identifier.split('.', 1)[0]
|
1279 |
+
|
1280 |
+
parts = identifier.split(sep)
|
1281 |
+
lang = parts.pop(0).lower()
|
1282 |
+
if not lang.isalpha():
|
1283 |
+
raise ValueError(f"expected only letters, got {lang!r}")
|
1284 |
+
|
1285 |
+
script = territory = variant = None
|
1286 |
+
if parts and len(parts[0]) == 4 and parts[0].isalpha():
|
1287 |
+
script = parts.pop(0).title()
|
1288 |
+
|
1289 |
+
if parts:
|
1290 |
+
if len(parts[0]) == 2 and parts[0].isalpha():
|
1291 |
+
territory = parts.pop(0).upper()
|
1292 |
+
elif len(parts[0]) == 3 and parts[0].isdigit():
|
1293 |
+
territory = parts.pop(0)
|
1294 |
+
|
1295 |
+
if parts and (
|
1296 |
+
len(parts[0]) == 4 and parts[0][0].isdigit() or
|
1297 |
+
len(parts[0]) >= 5 and parts[0][0].isalpha()
|
1298 |
+
):
|
1299 |
+
variant = parts.pop().upper()
|
1300 |
+
|
1301 |
+
if parts:
|
1302 |
+
raise ValueError(f"{identifier!r} is not a valid locale identifier")
|
1303 |
+
|
1304 |
+
# TODO(3.0): always return a 5-tuple
|
1305 |
+
if modifier:
|
1306 |
+
return lang, territory, script, variant, modifier
|
1307 |
+
else:
|
1308 |
+
return lang, territory, script, variant
|
1309 |
+
|
1310 |
+
|
1311 |
+
def get_locale_identifier(
|
1312 |
+
tup: tuple[str]
|
1313 |
+
| tuple[str, str | None]
|
1314 |
+
| tuple[str, str | None, str | None]
|
1315 |
+
| tuple[str, str | None, str | None, str | None]
|
1316 |
+
| tuple[str, str | None, str | None, str | None, str | None],
|
1317 |
+
sep: str = "_",
|
1318 |
+
) -> str:
|
1319 |
+
"""The reverse of :func:`parse_locale`. It creates a locale identifier out
|
1320 |
+
of a ``(language, territory, script, variant, modifier)`` tuple. Items can be set to
|
1321 |
+
``None`` and trailing ``None``\\s can also be left out of the tuple.
|
1322 |
+
|
1323 |
+
>>> get_locale_identifier(('de', 'DE', None, '1999', 'custom'))
|
1324 |
+
'de_DE_1999@custom'
|
1325 |
+
>>> get_locale_identifier(('fi', None, None, None, 'custom'))
|
1326 |
+
'fi@custom'
|
1327 |
+
|
1328 |
+
|
1329 |
+
.. versionadded:: 1.0
|
1330 |
+
|
1331 |
+
:param tup: the tuple as returned by :func:`parse_locale`.
|
1332 |
+
:param sep: the separator for the identifier.
|
1333 |
+
"""
|
1334 |
+
tup = tuple(tup[:5]) # type: ignore # length should be no more than 5
|
1335 |
+
lang, territory, script, variant, modifier = tup + (None,) * (5 - len(tup))
|
1336 |
+
ret = sep.join(filter(None, (lang, script, territory, variant)))
|
1337 |
+
return f'{ret}@{modifier}' if modifier else ret
|
lib/python3.10/site-packages/babel/d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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
babel.dates
|
3 |
+
~~~~~~~~~~~
|
4 |
+
|
5 |
+
Locale dependent formatting and parsing of dates and times.
|
6 |
+
|
7 |
+
The default locale for the functions in this module is determined by the
|
8 |
+
following environment variables, in that order:
|
9 |
+
|
10 |
+
* ``LC_TIME``,
|
11 |
+
* ``LC_ALL``, and
|
12 |
+
* ``LANG``
|
13 |
+
|
14 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
15 |
+
:license: BSD, see LICENSE for more details.
|
16 |
+
"""
|
17 |
+
|
18 |
+
from __future__ import annotations
|
19 |
+
|
20 |
+
import math
|
21 |
+
import re
|
22 |
+
import warnings
|
23 |
+
from functools import lru_cache
|
24 |
+
from typing import TYPE_CHECKING, Literal, SupportsInt
|
25 |
+
|
26 |
+
try:
|
27 |
+
import pytz
|
28 |
+
except ModuleNotFoundError:
|
29 |
+
pytz = None
|
30 |
+
import zoneinfo
|
31 |
+
|
32 |
+
import datetime
|
33 |
+
from collections.abc import Iterable
|
34 |
+
|
35 |
+
from babel import localtime
|
36 |
+
from babel.core import Locale, default_locale, get_global
|
37 |
+
from babel.localedata import LocaleDataDict
|
38 |
+
|
39 |
+
if TYPE_CHECKING:
|
40 |
+
from typing_extensions import TypeAlias
|
41 |
+
_Instant: TypeAlias = datetime.date | datetime.time | float | None
|
42 |
+
_PredefinedTimeFormat: TypeAlias = Literal['full', 'long', 'medium', 'short']
|
43 |
+
_Context: TypeAlias = Literal['format', 'stand-alone']
|
44 |
+
_DtOrTzinfo: TypeAlias = datetime.datetime | datetime.tzinfo | str | int | datetime.time | None
|
45 |
+
|
46 |
+
# "If a given short metazone form is known NOT to be understood in a given
|
47 |
+
# locale and the parent locale has this value such that it would normally
|
48 |
+
# be inherited, the inheritance of this value can be explicitly disabled by
|
49 |
+
# use of the 'no inheritance marker' as the value, which is 3 simultaneous [sic]
|
50 |
+
# empty set characters ( U+2205 )."
|
51 |
+
# - https://www.unicode.org/reports/tr35/tr35-dates.html#Metazone_Names
|
52 |
+
|
53 |
+
NO_INHERITANCE_MARKER = '\u2205\u2205\u2205'
|
54 |
+
|
55 |
+
UTC = datetime.timezone.utc
|
56 |
+
LOCALTZ = localtime.LOCALTZ
|
57 |
+
|
58 |
+
LC_TIME = default_locale('LC_TIME')
|
59 |
+
|
60 |
+
|
61 |
+
def _localize(tz: datetime.tzinfo, dt: datetime.datetime) -> datetime.datetime:
|
62 |
+
# Support localizing with both pytz and zoneinfo tzinfos
|
63 |
+
# nothing to do
|
64 |
+
if dt.tzinfo is tz:
|
65 |
+
return dt
|
66 |
+
|
67 |
+
if hasattr(tz, 'localize'): # pytz
|
68 |
+
return tz.localize(dt)
|
69 |
+
|
70 |
+
if dt.tzinfo is None:
|
71 |
+
# convert naive to localized
|
72 |
+
return dt.replace(tzinfo=tz)
|
73 |
+
|
74 |
+
# convert timezones
|
75 |
+
return dt.astimezone(tz)
|
76 |
+
|
77 |
+
|
78 |
+
def _get_dt_and_tzinfo(dt_or_tzinfo: _DtOrTzinfo) -> tuple[datetime.datetime | None, datetime.tzinfo]:
|
79 |
+
"""
|
80 |
+
Parse a `dt_or_tzinfo` value into a datetime and a tzinfo.
|
81 |
+
|
82 |
+
See the docs for this function's callers for semantics.
|
83 |
+
|
84 |
+
:rtype: tuple[datetime, tzinfo]
|
85 |
+
"""
|
86 |
+
if dt_or_tzinfo is None:
|
87 |
+
dt = datetime.datetime.now()
|
88 |
+
tzinfo = LOCALTZ
|
89 |
+
elif isinstance(dt_or_tzinfo, str):
|
90 |
+
dt = None
|
91 |
+
tzinfo = get_timezone(dt_or_tzinfo)
|
92 |
+
elif isinstance(dt_or_tzinfo, int):
|
93 |
+
dt = None
|
94 |
+
tzinfo = UTC
|
95 |
+
elif isinstance(dt_or_tzinfo, (datetime.datetime, datetime.time)):
|
96 |
+
dt = _get_datetime(dt_or_tzinfo)
|
97 |
+
tzinfo = dt.tzinfo if dt.tzinfo is not None else UTC
|
98 |
+
else:
|
99 |
+
dt = None
|
100 |
+
tzinfo = dt_or_tzinfo
|
101 |
+
return dt, tzinfo
|
102 |
+
|
103 |
+
|
104 |
+
def _get_tz_name(dt_or_tzinfo: _DtOrTzinfo) -> str:
|
105 |
+
"""
|
106 |
+
Get the timezone name out of a time, datetime, or tzinfo object.
|
107 |
+
|
108 |
+
:rtype: str
|
109 |
+
"""
|
110 |
+
dt, tzinfo = _get_dt_and_tzinfo(dt_or_tzinfo)
|
111 |
+
if hasattr(tzinfo, 'zone'): # pytz object
|
112 |
+
return tzinfo.zone
|
113 |
+
elif hasattr(tzinfo, 'key') and tzinfo.key is not None: # ZoneInfo object
|
114 |
+
return tzinfo.key
|
115 |
+
else:
|
116 |
+
return tzinfo.tzname(dt or datetime.datetime.now(UTC))
|
117 |
+
|
118 |
+
|
119 |
+
def _get_datetime(instant: _Instant) -> datetime.datetime:
|
120 |
+
"""
|
121 |
+
Get a datetime out of an "instant" (date, time, datetime, number).
|
122 |
+
|
123 |
+
.. warning:: The return values of this function may depend on the system clock.
|
124 |
+
|
125 |
+
If the instant is None, the current moment is used.
|
126 |
+
If the instant is a time, it's augmented with today's date.
|
127 |
+
|
128 |
+
Dates are converted to naive datetimes with midnight as the time component.
|
129 |
+
|
130 |
+
>>> from datetime import date, datetime
|
131 |
+
>>> _get_datetime(date(2015, 1, 1))
|
132 |
+
datetime.datetime(2015, 1, 1, 0, 0)
|
133 |
+
|
134 |
+
UNIX timestamps are converted to datetimes.
|
135 |
+
|
136 |
+
>>> _get_datetime(1400000000)
|
137 |
+
datetime.datetime(2014, 5, 13, 16, 53, 20)
|
138 |
+
|
139 |
+
Other values are passed through as-is.
|
140 |
+
|
141 |
+
>>> x = datetime(2015, 1, 1)
|
142 |
+
>>> _get_datetime(x) is x
|
143 |
+
True
|
144 |
+
|
145 |
+
:param instant: date, time, datetime, integer, float or None
|
146 |
+
:type instant: date|time|datetime|int|float|None
|
147 |
+
:return: a datetime
|
148 |
+
:rtype: datetime
|
149 |
+
"""
|
150 |
+
if instant is None:
|
151 |
+
return datetime.datetime.now(UTC).replace(tzinfo=None)
|
152 |
+
elif isinstance(instant, (int, float)):
|
153 |
+
return datetime.datetime.fromtimestamp(instant, UTC).replace(tzinfo=None)
|
154 |
+
elif isinstance(instant, datetime.time):
|
155 |
+
return datetime.datetime.combine(datetime.date.today(), instant)
|
156 |
+
elif isinstance(instant, datetime.date) and not isinstance(instant, datetime.datetime):
|
157 |
+
return datetime.datetime.combine(instant, datetime.time())
|
158 |
+
# TODO (3.x): Add an assertion/type check for this fallthrough branch:
|
159 |
+
return instant
|
160 |
+
|
161 |
+
|
162 |
+
def _ensure_datetime_tzinfo(dt: datetime.datetime, tzinfo: datetime.tzinfo | None = None) -> datetime.datetime:
|
163 |
+
"""
|
164 |
+
Ensure the datetime passed has an attached tzinfo.
|
165 |
+
|
166 |
+
If the datetime is tz-naive to begin with, UTC is attached.
|
167 |
+
|
168 |
+
If a tzinfo is passed in, the datetime is normalized to that timezone.
|
169 |
+
|
170 |
+
>>> from datetime import datetime
|
171 |
+
>>> _get_tz_name(_ensure_datetime_tzinfo(datetime(2015, 1, 1)))
|
172 |
+
'UTC'
|
173 |
+
|
174 |
+
>>> tz = get_timezone("Europe/Stockholm")
|
175 |
+
>>> _ensure_datetime_tzinfo(datetime(2015, 1, 1, 13, 15, tzinfo=UTC), tzinfo=tz).hour
|
176 |
+
14
|
177 |
+
|
178 |
+
:param datetime: Datetime to augment.
|
179 |
+
:param tzinfo: optional tzinfo
|
180 |
+
:return: datetime with tzinfo
|
181 |
+
:rtype: datetime
|
182 |
+
"""
|
183 |
+
if dt.tzinfo is None:
|
184 |
+
dt = dt.replace(tzinfo=UTC)
|
185 |
+
if tzinfo is not None:
|
186 |
+
dt = dt.astimezone(get_timezone(tzinfo))
|
187 |
+
if hasattr(tzinfo, 'normalize'): # pytz
|
188 |
+
dt = tzinfo.normalize(dt)
|
189 |
+
return dt
|
190 |
+
|
191 |
+
|
192 |
+
def _get_time(
|
193 |
+
time: datetime.time | datetime.datetime | None,
|
194 |
+
tzinfo: datetime.tzinfo | None = None,
|
195 |
+
) -> datetime.time:
|
196 |
+
"""
|
197 |
+
Get a timezoned time from a given instant.
|
198 |
+
|
199 |
+
.. warning:: The return values of this function may depend on the system clock.
|
200 |
+
|
201 |
+
:param time: time, datetime or None
|
202 |
+
:rtype: time
|
203 |
+
"""
|
204 |
+
if time is None:
|
205 |
+
time = datetime.datetime.now(UTC)
|
206 |
+
elif isinstance(time, (int, float)):
|
207 |
+
time = datetime.datetime.fromtimestamp(time, UTC)
|
208 |
+
|
209 |
+
if time.tzinfo is None:
|
210 |
+
time = time.replace(tzinfo=UTC)
|
211 |
+
|
212 |
+
if isinstance(time, datetime.datetime):
|
213 |
+
if tzinfo is not None:
|
214 |
+
time = time.astimezone(tzinfo)
|
215 |
+
if hasattr(tzinfo, 'normalize'): # pytz
|
216 |
+
time = tzinfo.normalize(time)
|
217 |
+
time = time.timetz()
|
218 |
+
elif tzinfo is not None:
|
219 |
+
time = time.replace(tzinfo=tzinfo)
|
220 |
+
return time
|
221 |
+
|
222 |
+
|
223 |
+
def get_timezone(zone: str | datetime.tzinfo | None = None) -> datetime.tzinfo:
|
224 |
+
"""Looks up a timezone by name and returns it. The timezone object
|
225 |
+
returned comes from ``pytz`` or ``zoneinfo``, whichever is available.
|
226 |
+
It corresponds to the `tzinfo` interface and can be used with all of
|
227 |
+
the functions of Babel that operate with dates.
|
228 |
+
|
229 |
+
If a timezone is not known a :exc:`LookupError` is raised. If `zone`
|
230 |
+
is ``None`` a local zone object is returned.
|
231 |
+
|
232 |
+
:param zone: the name of the timezone to look up. If a timezone object
|
233 |
+
itself is passed in, it's returned unchanged.
|
234 |
+
"""
|
235 |
+
if zone is None:
|
236 |
+
return LOCALTZ
|
237 |
+
if not isinstance(zone, str):
|
238 |
+
return zone
|
239 |
+
|
240 |
+
if pytz:
|
241 |
+
try:
|
242 |
+
return pytz.timezone(zone)
|
243 |
+
except pytz.UnknownTimeZoneError as e:
|
244 |
+
exc = e
|
245 |
+
else:
|
246 |
+
assert zoneinfo
|
247 |
+
try:
|
248 |
+
return zoneinfo.ZoneInfo(zone)
|
249 |
+
except zoneinfo.ZoneInfoNotFoundError as e:
|
250 |
+
exc = e
|
251 |
+
|
252 |
+
raise LookupError(f"Unknown timezone {zone}") from exc
|
253 |
+
|
254 |
+
|
255 |
+
def get_period_names(
|
256 |
+
width: Literal['abbreviated', 'narrow', 'wide'] = 'wide',
|
257 |
+
context: _Context = 'stand-alone',
|
258 |
+
locale: Locale | str | None = None,
|
259 |
+
) -> LocaleDataDict:
|
260 |
+
"""Return the names for day periods (AM/PM) used by the locale.
|
261 |
+
|
262 |
+
>>> get_period_names(locale='en_US')['am']
|
263 |
+
u'AM'
|
264 |
+
|
265 |
+
:param width: the width to use, one of "abbreviated", "narrow", or "wide"
|
266 |
+
:param context: the context, either "format" or "stand-alone"
|
267 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
268 |
+
"""
|
269 |
+
return Locale.parse(locale or LC_TIME).day_periods[context][width]
|
270 |
+
|
271 |
+
|
272 |
+
def get_day_names(
|
273 |
+
width: Literal['abbreviated', 'narrow', 'short', 'wide'] = 'wide',
|
274 |
+
context: _Context = 'format',
|
275 |
+
locale: Locale | str | None = None,
|
276 |
+
) -> LocaleDataDict:
|
277 |
+
"""Return the day names used by the locale for the specified format.
|
278 |
+
|
279 |
+
>>> get_day_names('wide', locale='en_US')[1]
|
280 |
+
u'Tuesday'
|
281 |
+
>>> get_day_names('short', locale='en_US')[1]
|
282 |
+
u'Tu'
|
283 |
+
>>> get_day_names('abbreviated', locale='es')[1]
|
284 |
+
u'mar'
|
285 |
+
>>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
|
286 |
+
u'D'
|
287 |
+
|
288 |
+
:param width: the width to use, one of "wide", "abbreviated", "short" or "narrow"
|
289 |
+
:param context: the context, either "format" or "stand-alone"
|
290 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
291 |
+
"""
|
292 |
+
return Locale.parse(locale or LC_TIME).days[context][width]
|
293 |
+
|
294 |
+
|
295 |
+
def get_month_names(
|
296 |
+
width: Literal['abbreviated', 'narrow', 'wide'] = 'wide',
|
297 |
+
context: _Context = 'format',
|
298 |
+
locale: Locale | str | None = None,
|
299 |
+
) -> LocaleDataDict:
|
300 |
+
"""Return the month names used by the locale for the specified format.
|
301 |
+
|
302 |
+
>>> get_month_names('wide', locale='en_US')[1]
|
303 |
+
u'January'
|
304 |
+
>>> get_month_names('abbreviated', locale='es')[1]
|
305 |
+
u'ene'
|
306 |
+
>>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
|
307 |
+
u'J'
|
308 |
+
|
309 |
+
:param width: the width to use, one of "wide", "abbreviated", or "narrow"
|
310 |
+
:param context: the context, either "format" or "stand-alone"
|
311 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
312 |
+
"""
|
313 |
+
return Locale.parse(locale or LC_TIME).months[context][width]
|
314 |
+
|
315 |
+
|
316 |
+
def get_quarter_names(
|
317 |
+
width: Literal['abbreviated', 'narrow', 'wide'] = 'wide',
|
318 |
+
context: _Context = 'format',
|
319 |
+
locale: Locale | str | None = None,
|
320 |
+
) -> LocaleDataDict:
|
321 |
+
"""Return the quarter names used by the locale for the specified format.
|
322 |
+
|
323 |
+
>>> get_quarter_names('wide', locale='en_US')[1]
|
324 |
+
u'1st quarter'
|
325 |
+
>>> get_quarter_names('abbreviated', locale='de_DE')[1]
|
326 |
+
u'Q1'
|
327 |
+
>>> get_quarter_names('narrow', locale='de_DE')[1]
|
328 |
+
u'1'
|
329 |
+
|
330 |
+
:param width: the width to use, one of "wide", "abbreviated", or "narrow"
|
331 |
+
:param context: the context, either "format" or "stand-alone"
|
332 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
333 |
+
"""
|
334 |
+
return Locale.parse(locale or LC_TIME).quarters[context][width]
|
335 |
+
|
336 |
+
|
337 |
+
def get_era_names(
|
338 |
+
width: Literal['abbreviated', 'narrow', 'wide'] = 'wide',
|
339 |
+
locale: Locale | str | None = None,
|
340 |
+
) -> LocaleDataDict:
|
341 |
+
"""Return the era names used by the locale for the specified format.
|
342 |
+
|
343 |
+
>>> get_era_names('wide', locale='en_US')[1]
|
344 |
+
u'Anno Domini'
|
345 |
+
>>> get_era_names('abbreviated', locale='de_DE')[1]
|
346 |
+
u'n. Chr.'
|
347 |
+
|
348 |
+
:param width: the width to use, either "wide", "abbreviated", or "narrow"
|
349 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
350 |
+
"""
|
351 |
+
return Locale.parse(locale or LC_TIME).eras[width]
|
352 |
+
|
353 |
+
|
354 |
+
def get_date_format(
|
355 |
+
format: _PredefinedTimeFormat = 'medium',
|
356 |
+
locale: Locale | str | None = None,
|
357 |
+
) -> DateTimePattern:
|
358 |
+
"""Return the date formatting patterns used by the locale for the specified
|
359 |
+
format.
|
360 |
+
|
361 |
+
>>> get_date_format(locale='en_US')
|
362 |
+
<DateTimePattern u'MMM d, y'>
|
363 |
+
>>> get_date_format('full', locale='de_DE')
|
364 |
+
<DateTimePattern u'EEEE, d. MMMM y'>
|
365 |
+
|
366 |
+
:param format: the format to use, one of "full", "long", "medium", or
|
367 |
+
"short"
|
368 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
369 |
+
"""
|
370 |
+
return Locale.parse(locale or LC_TIME).date_formats[format]
|
371 |
+
|
372 |
+
|
373 |
+
def get_datetime_format(
|
374 |
+
format: _PredefinedTimeFormat = 'medium',
|
375 |
+
locale: Locale | str | None = None,
|
376 |
+
) -> DateTimePattern:
|
377 |
+
"""Return the datetime formatting patterns used by the locale for the
|
378 |
+
specified format.
|
379 |
+
|
380 |
+
>>> get_datetime_format(locale='en_US')
|
381 |
+
u'{1}, {0}'
|
382 |
+
|
383 |
+
:param format: the format to use, one of "full", "long", "medium", or
|
384 |
+
"short"
|
385 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
386 |
+
"""
|
387 |
+
patterns = Locale.parse(locale or LC_TIME).datetime_formats
|
388 |
+
if format not in patterns:
|
389 |
+
format = None
|
390 |
+
return patterns[format]
|
391 |
+
|
392 |
+
|
393 |
+
def get_time_format(
|
394 |
+
format: _PredefinedTimeFormat = 'medium',
|
395 |
+
locale: Locale | str | None = None,
|
396 |
+
) -> DateTimePattern:
|
397 |
+
"""Return the time formatting patterns used by the locale for the specified
|
398 |
+
format.
|
399 |
+
|
400 |
+
>>> get_time_format(locale='en_US')
|
401 |
+
<DateTimePattern u'h:mm:ss\u202fa'>
|
402 |
+
>>> get_time_format('full', locale='de_DE')
|
403 |
+
<DateTimePattern u'HH:mm:ss zzzz'>
|
404 |
+
|
405 |
+
:param format: the format to use, one of "full", "long", "medium", or
|
406 |
+
"short"
|
407 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
408 |
+
"""
|
409 |
+
return Locale.parse(locale or LC_TIME).time_formats[format]
|
410 |
+
|
411 |
+
|
412 |
+
def get_timezone_gmt(
|
413 |
+
datetime: _Instant = None,
|
414 |
+
width: Literal['long', 'short', 'iso8601', 'iso8601_short'] = 'long',
|
415 |
+
locale: Locale | str | None = None,
|
416 |
+
return_z: bool = False,
|
417 |
+
) -> str:
|
418 |
+
"""Return the timezone associated with the given `datetime` object formatted
|
419 |
+
as string indicating the offset from GMT.
|
420 |
+
|
421 |
+
>>> from datetime import datetime
|
422 |
+
>>> dt = datetime(2007, 4, 1, 15, 30)
|
423 |
+
>>> get_timezone_gmt(dt, locale='en')
|
424 |
+
u'GMT+00:00'
|
425 |
+
>>> get_timezone_gmt(dt, locale='en', return_z=True)
|
426 |
+
'Z'
|
427 |
+
>>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
|
428 |
+
u'+00'
|
429 |
+
>>> tz = get_timezone('America/Los_Angeles')
|
430 |
+
>>> dt = _localize(tz, datetime(2007, 4, 1, 15, 30))
|
431 |
+
>>> get_timezone_gmt(dt, locale='en')
|
432 |
+
u'GMT-07:00'
|
433 |
+
>>> get_timezone_gmt(dt, 'short', locale='en')
|
434 |
+
u'-0700'
|
435 |
+
>>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
|
436 |
+
u'-07'
|
437 |
+
|
438 |
+
The long format depends on the locale, for example in France the acronym
|
439 |
+
UTC string is used instead of GMT:
|
440 |
+
|
441 |
+
>>> get_timezone_gmt(dt, 'long', locale='fr_FR')
|
442 |
+
u'UTC-07:00'
|
443 |
+
|
444 |
+
.. versionadded:: 0.9
|
445 |
+
|
446 |
+
:param datetime: the ``datetime`` object; if `None`, the current date and
|
447 |
+
time in UTC is used
|
448 |
+
:param width: either "long" or "short" or "iso8601" or "iso8601_short"
|
449 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
450 |
+
:param return_z: True or False; Function returns indicator "Z"
|
451 |
+
when local time offset is 0
|
452 |
+
"""
|
453 |
+
datetime = _ensure_datetime_tzinfo(_get_datetime(datetime))
|
454 |
+
locale = Locale.parse(locale or LC_TIME)
|
455 |
+
|
456 |
+
offset = datetime.tzinfo.utcoffset(datetime)
|
457 |
+
seconds = offset.days * 24 * 60 * 60 + offset.seconds
|
458 |
+
hours, seconds = divmod(seconds, 3600)
|
459 |
+
if return_z and hours == 0 and seconds == 0:
|
460 |
+
return 'Z'
|
461 |
+
elif seconds == 0 and width == 'iso8601_short':
|
462 |
+
return '%+03d' % hours
|
463 |
+
elif width == 'short' or width == 'iso8601_short':
|
464 |
+
pattern = '%+03d%02d'
|
465 |
+
elif width == 'iso8601':
|
466 |
+
pattern = '%+03d:%02d'
|
467 |
+
else:
|
468 |
+
pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
|
469 |
+
return pattern % (hours, seconds // 60)
|
470 |
+
|
471 |
+
|
472 |
+
def get_timezone_location(
|
473 |
+
dt_or_tzinfo: _DtOrTzinfo = None,
|
474 |
+
locale: Locale | str | None = None,
|
475 |
+
return_city: bool = False,
|
476 |
+
) -> str:
|
477 |
+
"""Return a representation of the given timezone using "location format".
|
478 |
+
|
479 |
+
The result depends on both the local display name of the country and the
|
480 |
+
city associated with the time zone:
|
481 |
+
|
482 |
+
>>> tz = get_timezone('America/St_Johns')
|
483 |
+
>>> print(get_timezone_location(tz, locale='de_DE'))
|
484 |
+
Kanada (St. John’s) (Ortszeit)
|
485 |
+
>>> print(get_timezone_location(tz, locale='en'))
|
486 |
+
Canada (St. John’s) Time
|
487 |
+
>>> print(get_timezone_location(tz, locale='en', return_city=True))
|
488 |
+
St. John’s
|
489 |
+
>>> tz = get_timezone('America/Mexico_City')
|
490 |
+
>>> get_timezone_location(tz, locale='de_DE')
|
491 |
+
u'Mexiko (Mexiko-Stadt) (Ortszeit)'
|
492 |
+
|
493 |
+
If the timezone is associated with a country that uses only a single
|
494 |
+
timezone, just the localized country name is returned:
|
495 |
+
|
496 |
+
>>> tz = get_timezone('Europe/Berlin')
|
497 |
+
>>> get_timezone_name(tz, locale='de_DE')
|
498 |
+
u'Mitteleurop\\xe4ische Zeit'
|
499 |
+
|
500 |
+
.. versionadded:: 0.9
|
501 |
+
|
502 |
+
:param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
|
503 |
+
the timezone; if `None`, the current date and time in
|
504 |
+
UTC is assumed
|
505 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
506 |
+
:param return_city: True or False, if True then return exemplar city (location)
|
507 |
+
for the time zone
|
508 |
+
:return: the localized timezone name using location format
|
509 |
+
|
510 |
+
"""
|
511 |
+
locale = Locale.parse(locale or LC_TIME)
|
512 |
+
|
513 |
+
zone = _get_tz_name(dt_or_tzinfo)
|
514 |
+
|
515 |
+
# Get the canonical time-zone code
|
516 |
+
zone = get_global('zone_aliases').get(zone, zone)
|
517 |
+
|
518 |
+
info = locale.time_zones.get(zone, {})
|
519 |
+
|
520 |
+
# Otherwise, if there is only one timezone for the country, return the
|
521 |
+
# localized country name
|
522 |
+
region_format = locale.zone_formats['region']
|
523 |
+
territory = get_global('zone_territories').get(zone)
|
524 |
+
if territory not in locale.territories:
|
525 |
+
territory = 'ZZ' # invalid/unknown
|
526 |
+
territory_name = locale.territories[territory]
|
527 |
+
if not return_city and territory and len(get_global('territory_zones').get(territory, [])) == 1:
|
528 |
+
return region_format % territory_name
|
529 |
+
|
530 |
+
# Otherwise, include the city in the output
|
531 |
+
fallback_format = locale.zone_formats['fallback']
|
532 |
+
if 'city' in info:
|
533 |
+
city_name = info['city']
|
534 |
+
else:
|
535 |
+
metazone = get_global('meta_zones').get(zone)
|
536 |
+
metazone_info = locale.meta_zones.get(metazone, {})
|
537 |
+
if 'city' in metazone_info:
|
538 |
+
city_name = metazone_info['city']
|
539 |
+
elif '/' in zone:
|
540 |
+
city_name = zone.split('/', 1)[1].replace('_', ' ')
|
541 |
+
else:
|
542 |
+
city_name = zone.replace('_', ' ')
|
543 |
+
|
544 |
+
if return_city:
|
545 |
+
return city_name
|
546 |
+
return region_format % (fallback_format % {
|
547 |
+
'0': city_name,
|
548 |
+
'1': territory_name,
|
549 |
+
})
|
550 |
+
|
551 |
+
|
552 |
+
def get_timezone_name(
|
553 |
+
dt_or_tzinfo: _DtOrTzinfo = None,
|
554 |
+
width: Literal['long', 'short'] = 'long',
|
555 |
+
uncommon: bool = False,
|
556 |
+
locale: Locale | str | None = None,
|
557 |
+
zone_variant: Literal['generic', 'daylight', 'standard'] | None = None,
|
558 |
+
return_zone: bool = False,
|
559 |
+
) -> str:
|
560 |
+
r"""Return the localized display name for the given timezone. The timezone
|
561 |
+
may be specified using a ``datetime`` or `tzinfo` object.
|
562 |
+
|
563 |
+
>>> from datetime import time
|
564 |
+
>>> dt = time(15, 30, tzinfo=get_timezone('America/Los_Angeles'))
|
565 |
+
>>> get_timezone_name(dt, locale='en_US') # doctest: +SKIP
|
566 |
+
u'Pacific Standard Time'
|
567 |
+
>>> get_timezone_name(dt, locale='en_US', return_zone=True)
|
568 |
+
'America/Los_Angeles'
|
569 |
+
>>> get_timezone_name(dt, width='short', locale='en_US') # doctest: +SKIP
|
570 |
+
u'PST'
|
571 |
+
|
572 |
+
If this function gets passed only a `tzinfo` object and no concrete
|
573 |
+
`datetime`, the returned display name is independent of daylight savings
|
574 |
+
time. This can be used for example for selecting timezones, or to set the
|
575 |
+
time of events that recur across DST changes:
|
576 |
+
|
577 |
+
>>> tz = get_timezone('America/Los_Angeles')
|
578 |
+
>>> get_timezone_name(tz, locale='en_US')
|
579 |
+
u'Pacific Time'
|
580 |
+
>>> get_timezone_name(tz, 'short', locale='en_US')
|
581 |
+
u'PT'
|
582 |
+
|
583 |
+
If no localized display name for the timezone is available, and the timezone
|
584 |
+
is associated with a country that uses only a single timezone, the name of
|
585 |
+
that country is returned, formatted according to the locale:
|
586 |
+
|
587 |
+
>>> tz = get_timezone('Europe/Berlin')
|
588 |
+
>>> get_timezone_name(tz, locale='de_DE')
|
589 |
+
u'Mitteleurop\xe4ische Zeit'
|
590 |
+
>>> get_timezone_name(tz, locale='pt_BR')
|
591 |
+
u'Hor\xe1rio da Europa Central'
|
592 |
+
|
593 |
+
On the other hand, if the country uses multiple timezones, the city is also
|
594 |
+
included in the representation:
|
595 |
+
|
596 |
+
>>> tz = get_timezone('America/St_Johns')
|
597 |
+
>>> get_timezone_name(tz, locale='de_DE')
|
598 |
+
u'Neufundland-Zeit'
|
599 |
+
|
600 |
+
Note that short format is currently not supported for all timezones and
|
601 |
+
all locales. This is partially because not every timezone has a short
|
602 |
+
code in every locale. In that case it currently falls back to the long
|
603 |
+
format.
|
604 |
+
|
605 |
+
For more information see `LDML Appendix J: Time Zone Display Names
|
606 |
+
<https://www.unicode.org/reports/tr35/#Time_Zone_Fallback>`_
|
607 |
+
|
608 |
+
.. versionadded:: 0.9
|
609 |
+
|
610 |
+
.. versionchanged:: 1.0
|
611 |
+
Added `zone_variant` support.
|
612 |
+
|
613 |
+
:param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
|
614 |
+
the timezone; if a ``tzinfo`` object is used, the
|
615 |
+
resulting display name will be generic, i.e.
|
616 |
+
independent of daylight savings time; if `None`, the
|
617 |
+
current date in UTC is assumed
|
618 |
+
:param width: either "long" or "short"
|
619 |
+
:param uncommon: deprecated and ignored
|
620 |
+
:param zone_variant: defines the zone variation to return. By default the
|
621 |
+
variation is defined from the datetime object
|
622 |
+
passed in. If no datetime object is passed in, the
|
623 |
+
``'generic'`` variation is assumed. The following
|
624 |
+
values are valid: ``'generic'``, ``'daylight'`` and
|
625 |
+
``'standard'``.
|
626 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
627 |
+
:param return_zone: True or False. If true then function
|
628 |
+
returns long time zone ID
|
629 |
+
"""
|
630 |
+
dt, tzinfo = _get_dt_and_tzinfo(dt_or_tzinfo)
|
631 |
+
locale = Locale.parse(locale or LC_TIME)
|
632 |
+
|
633 |
+
zone = _get_tz_name(dt_or_tzinfo)
|
634 |
+
|
635 |
+
if zone_variant is None:
|
636 |
+
if dt is None:
|
637 |
+
zone_variant = 'generic'
|
638 |
+
else:
|
639 |
+
dst = tzinfo.dst(dt)
|
640 |
+
zone_variant = "daylight" if dst else "standard"
|
641 |
+
else:
|
642 |
+
if zone_variant not in ('generic', 'standard', 'daylight'):
|
643 |
+
raise ValueError('Invalid zone variation')
|
644 |
+
|
645 |
+
# Get the canonical time-zone code
|
646 |
+
zone = get_global('zone_aliases').get(zone, zone)
|
647 |
+
if return_zone:
|
648 |
+
return zone
|
649 |
+
info = locale.time_zones.get(zone, {})
|
650 |
+
# Try explicitly translated zone names first
|
651 |
+
if width in info and zone_variant in info[width]:
|
652 |
+
return info[width][zone_variant]
|
653 |
+
|
654 |
+
metazone = get_global('meta_zones').get(zone)
|
655 |
+
if metazone:
|
656 |
+
metazone_info = locale.meta_zones.get(metazone, {})
|
657 |
+
if width in metazone_info:
|
658 |
+
name = metazone_info[width].get(zone_variant)
|
659 |
+
if width == 'short' and name == NO_INHERITANCE_MARKER:
|
660 |
+
# If the short form is marked no-inheritance,
|
661 |
+
# try to fall back to the long name instead.
|
662 |
+
name = metazone_info.get('long', {}).get(zone_variant)
|
663 |
+
if name:
|
664 |
+
return name
|
665 |
+
|
666 |
+
# If we have a concrete datetime, we assume that the result can't be
|
667 |
+
# independent of daylight savings time, so we return the GMT offset
|
668 |
+
if dt is not None:
|
669 |
+
return get_timezone_gmt(dt, width=width, locale=locale)
|
670 |
+
|
671 |
+
return get_timezone_location(dt_or_tzinfo, locale=locale)
|
672 |
+
|
673 |
+
|
674 |
+
def format_date(
|
675 |
+
date: datetime.date | None = None,
|
676 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
677 |
+
locale: Locale | str | None = None,
|
678 |
+
) -> str:
|
679 |
+
"""Return a date formatted according to the given pattern.
|
680 |
+
|
681 |
+
>>> from datetime import date
|
682 |
+
>>> d = date(2007, 4, 1)
|
683 |
+
>>> format_date(d, locale='en_US')
|
684 |
+
u'Apr 1, 2007'
|
685 |
+
>>> format_date(d, format='full', locale='de_DE')
|
686 |
+
u'Sonntag, 1. April 2007'
|
687 |
+
|
688 |
+
If you don't want to use the locale default formats, you can specify a
|
689 |
+
custom date pattern:
|
690 |
+
|
691 |
+
>>> format_date(d, "EEE, MMM d, ''yy", locale='en')
|
692 |
+
u"Sun, Apr 1, '07"
|
693 |
+
|
694 |
+
:param date: the ``date`` or ``datetime`` object; if `None`, the current
|
695 |
+
date is used
|
696 |
+
:param format: one of "full", "long", "medium", or "short", or a custom
|
697 |
+
date/time pattern
|
698 |
+
:param locale: a `Locale` object or a locale identifier. Defaults to the system time locale.
|
699 |
+
"""
|
700 |
+
if date is None:
|
701 |
+
date = datetime.date.today()
|
702 |
+
elif isinstance(date, datetime.datetime):
|
703 |
+
date = date.date()
|
704 |
+
|
705 |
+
locale = Locale.parse(locale or LC_TIME)
|
706 |
+
if format in ('full', 'long', 'medium', 'short'):
|
707 |
+
format = get_date_format(format, locale=locale)
|
708 |
+
pattern = parse_pattern(format)
|
709 |
+
return pattern.apply(date, locale)
|
710 |
+
|
711 |
+
|
712 |
+
def format_datetime(
|
713 |
+
datetime: _Instant = None,
|
714 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
715 |
+
tzinfo: datetime.tzinfo | None = None,
|
716 |
+
locale: Locale | str | None = None,
|
717 |
+
) -> str:
|
718 |
+
r"""Return a date formatted according to the given pattern.
|
719 |
+
|
720 |
+
>>> from datetime import datetime
|
721 |
+
>>> dt = datetime(2007, 4, 1, 15, 30)
|
722 |
+
>>> format_datetime(dt, locale='en_US')
|
723 |
+
u'Apr 1, 2007, 3:30:00\u202fPM'
|
724 |
+
|
725 |
+
For any pattern requiring the display of the timezone:
|
726 |
+
|
727 |
+
>>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
|
728 |
+
... locale='fr_FR')
|
729 |
+
'dimanche 1 avril 2007, 17:30:00 heure d’été d’Europe centrale'
|
730 |
+
>>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
|
731 |
+
... tzinfo=get_timezone('US/Eastern'), locale='en')
|
732 |
+
u'2007.04.01 AD at 11:30:00 EDT'
|
733 |
+
|
734 |
+
:param datetime: the `datetime` object; if `None`, the current date and
|
735 |
+
time is used
|
736 |
+
:param format: one of "full", "long", "medium", or "short", or a custom
|
737 |
+
date/time pattern
|
738 |
+
:param tzinfo: the timezone to apply to the time for display
|
739 |
+
:param locale: a `Locale` object or a locale identifier. Defaults to the system time locale.
|
740 |
+
"""
|
741 |
+
datetime = _ensure_datetime_tzinfo(_get_datetime(datetime), tzinfo)
|
742 |
+
|
743 |
+
locale = Locale.parse(locale or LC_TIME)
|
744 |
+
if format in ('full', 'long', 'medium', 'short'):
|
745 |
+
return get_datetime_format(format, locale=locale) \
|
746 |
+
.replace("'", "") \
|
747 |
+
.replace('{0}', format_time(datetime, format, tzinfo=None,
|
748 |
+
locale=locale)) \
|
749 |
+
.replace('{1}', format_date(datetime, format, locale=locale))
|
750 |
+
else:
|
751 |
+
return parse_pattern(format).apply(datetime, locale)
|
752 |
+
|
753 |
+
|
754 |
+
def format_time(
|
755 |
+
time: datetime.time | datetime.datetime | float | None = None,
|
756 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
757 |
+
tzinfo: datetime.tzinfo | None = None,
|
758 |
+
locale: Locale | str | None = None,
|
759 |
+
) -> str:
|
760 |
+
r"""Return a time formatted according to the given pattern.
|
761 |
+
|
762 |
+
>>> from datetime import datetime, time
|
763 |
+
>>> t = time(15, 30)
|
764 |
+
>>> format_time(t, locale='en_US')
|
765 |
+
u'3:30:00\u202fPM'
|
766 |
+
>>> format_time(t, format='short', locale='de_DE')
|
767 |
+
u'15:30'
|
768 |
+
|
769 |
+
If you don't want to use the locale default formats, you can specify a
|
770 |
+
custom time pattern:
|
771 |
+
|
772 |
+
>>> format_time(t, "hh 'o''clock' a", locale='en')
|
773 |
+
u"03 o'clock PM"
|
774 |
+
|
775 |
+
For any pattern requiring the display of the time-zone a
|
776 |
+
timezone has to be specified explicitly:
|
777 |
+
|
778 |
+
>>> t = datetime(2007, 4, 1, 15, 30)
|
779 |
+
>>> tzinfo = get_timezone('Europe/Paris')
|
780 |
+
>>> t = _localize(tzinfo, t)
|
781 |
+
>>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
|
782 |
+
'15:30:00 heure d’été d’Europe centrale'
|
783 |
+
>>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=get_timezone('US/Eastern'),
|
784 |
+
... locale='en')
|
785 |
+
u"09 o'clock AM, Eastern Daylight Time"
|
786 |
+
|
787 |
+
As that example shows, when this function gets passed a
|
788 |
+
``datetime.datetime`` value, the actual time in the formatted string is
|
789 |
+
adjusted to the timezone specified by the `tzinfo` parameter. If the
|
790 |
+
``datetime`` is "naive" (i.e. it has no associated timezone information),
|
791 |
+
it is assumed to be in UTC.
|
792 |
+
|
793 |
+
These timezone calculations are **not** performed if the value is of type
|
794 |
+
``datetime.time``, as without date information there's no way to determine
|
795 |
+
what a given time would translate to in a different timezone without
|
796 |
+
information about whether daylight savings time is in effect or not. This
|
797 |
+
means that time values are left as-is, and the value of the `tzinfo`
|
798 |
+
parameter is only used to display the timezone name if needed:
|
799 |
+
|
800 |
+
>>> t = time(15, 30)
|
801 |
+
>>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
|
802 |
+
... locale='fr_FR') # doctest: +SKIP
|
803 |
+
u'15:30:00 heure normale d\u2019Europe centrale'
|
804 |
+
>>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'),
|
805 |
+
... locale='en_US') # doctest: +SKIP
|
806 |
+
u'3:30:00\u202fPM Eastern Standard Time'
|
807 |
+
|
808 |
+
:param time: the ``time`` or ``datetime`` object; if `None`, the current
|
809 |
+
time in UTC is used
|
810 |
+
:param format: one of "full", "long", "medium", or "short", or a custom
|
811 |
+
date/time pattern
|
812 |
+
:param tzinfo: the time-zone to apply to the time for display
|
813 |
+
:param locale: a `Locale` object or a locale identifier. Defaults to the system time locale.
|
814 |
+
"""
|
815 |
+
|
816 |
+
# get reference date for if we need to find the right timezone variant
|
817 |
+
# in the pattern
|
818 |
+
ref_date = time.date() if isinstance(time, datetime.datetime) else None
|
819 |
+
|
820 |
+
time = _get_time(time, tzinfo)
|
821 |
+
|
822 |
+
locale = Locale.parse(locale or LC_TIME)
|
823 |
+
if format in ('full', 'long', 'medium', 'short'):
|
824 |
+
format = get_time_format(format, locale=locale)
|
825 |
+
return parse_pattern(format).apply(time, locale, reference_date=ref_date)
|
826 |
+
|
827 |
+
|
828 |
+
def format_skeleton(
|
829 |
+
skeleton: str,
|
830 |
+
datetime: _Instant = None,
|
831 |
+
tzinfo: datetime.tzinfo | None = None,
|
832 |
+
fuzzy: bool = True,
|
833 |
+
locale: Locale | str | None = None,
|
834 |
+
) -> str:
|
835 |
+
r"""Return a time and/or date formatted according to the given pattern.
|
836 |
+
|
837 |
+
The skeletons are defined in the CLDR data and provide more flexibility
|
838 |
+
than the simple short/long/medium formats, but are a bit harder to use.
|
839 |
+
The are defined using the date/time symbols without order or punctuation
|
840 |
+
and map to a suitable format for the given locale.
|
841 |
+
|
842 |
+
>>> from datetime import datetime
|
843 |
+
>>> t = datetime(2007, 4, 1, 15, 30)
|
844 |
+
>>> format_skeleton('MMMEd', t, locale='fr')
|
845 |
+
u'dim. 1 avr.'
|
846 |
+
>>> format_skeleton('MMMEd', t, locale='en')
|
847 |
+
u'Sun, Apr 1'
|
848 |
+
>>> format_skeleton('yMMd', t, locale='fi') # yMMd is not in the Finnish locale; yMd gets used
|
849 |
+
u'1.4.2007'
|
850 |
+
>>> format_skeleton('yMMd', t, fuzzy=False, locale='fi') # yMMd is not in the Finnish locale, an error is thrown
|
851 |
+
Traceback (most recent call last):
|
852 |
+
...
|
853 |
+
KeyError: yMMd
|
854 |
+
>>> format_skeleton('GH', t, fuzzy=True, locale='fi_FI') # GH is not in the Finnish locale and there is no close match, an error is thrown
|
855 |
+
Traceback (most recent call last):
|
856 |
+
...
|
857 |
+
KeyError: None
|
858 |
+
|
859 |
+
After the skeleton is resolved to a pattern `format_datetime` is called so
|
860 |
+
all timezone processing etc is the same as for that.
|
861 |
+
|
862 |
+
:param skeleton: A date time skeleton as defined in the cldr data.
|
863 |
+
:param datetime: the ``time`` or ``datetime`` object; if `None`, the current
|
864 |
+
time in UTC is used
|
865 |
+
:param tzinfo: the time-zone to apply to the time for display
|
866 |
+
:param fuzzy: If the skeleton is not found, allow choosing a skeleton that's
|
867 |
+
close enough to it. If there is no close match, a `KeyError`
|
868 |
+
is thrown.
|
869 |
+
:param locale: a `Locale` object or a locale identifier. Defaults to the system time locale.
|
870 |
+
"""
|
871 |
+
locale = Locale.parse(locale or LC_TIME)
|
872 |
+
if fuzzy and skeleton not in locale.datetime_skeletons:
|
873 |
+
skeleton = match_skeleton(skeleton, locale.datetime_skeletons)
|
874 |
+
format = locale.datetime_skeletons[skeleton]
|
875 |
+
return format_datetime(datetime, format, tzinfo, locale)
|
876 |
+
|
877 |
+
|
878 |
+
TIMEDELTA_UNITS: tuple[tuple[str, int], ...] = (
|
879 |
+
('year', 3600 * 24 * 365),
|
880 |
+
('month', 3600 * 24 * 30),
|
881 |
+
('week', 3600 * 24 * 7),
|
882 |
+
('day', 3600 * 24),
|
883 |
+
('hour', 3600),
|
884 |
+
('minute', 60),
|
885 |
+
('second', 1),
|
886 |
+
)
|
887 |
+
|
888 |
+
|
889 |
+
def format_timedelta(
|
890 |
+
delta: datetime.timedelta | int,
|
891 |
+
granularity: Literal['year', 'month', 'week', 'day', 'hour', 'minute', 'second'] = 'second',
|
892 |
+
threshold: float = .85,
|
893 |
+
add_direction: bool = False,
|
894 |
+
format: Literal['narrow', 'short', 'medium', 'long'] = 'long',
|
895 |
+
locale: Locale | str | None = None,
|
896 |
+
) -> str:
|
897 |
+
"""Return a time delta according to the rules of the given locale.
|
898 |
+
|
899 |
+
>>> from datetime import timedelta
|
900 |
+
>>> format_timedelta(timedelta(weeks=12), locale='en_US')
|
901 |
+
u'3 months'
|
902 |
+
>>> format_timedelta(timedelta(seconds=1), locale='es')
|
903 |
+
u'1 segundo'
|
904 |
+
|
905 |
+
The granularity parameter can be provided to alter the lowest unit
|
906 |
+
presented, which defaults to a second.
|
907 |
+
|
908 |
+
>>> format_timedelta(timedelta(hours=3), granularity='day', locale='en_US')
|
909 |
+
u'1 day'
|
910 |
+
|
911 |
+
The threshold parameter can be used to determine at which value the
|
912 |
+
presentation switches to the next higher unit. A higher threshold factor
|
913 |
+
means the presentation will switch later. For example:
|
914 |
+
|
915 |
+
>>> format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
|
916 |
+
u'1 day'
|
917 |
+
>>> format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
|
918 |
+
u'23 hours'
|
919 |
+
|
920 |
+
In addition directional information can be provided that informs
|
921 |
+
the user if the date is in the past or in the future:
|
922 |
+
|
923 |
+
>>> format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
|
924 |
+
u'in 1 hour'
|
925 |
+
>>> format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
|
926 |
+
u'1 hour ago'
|
927 |
+
|
928 |
+
The format parameter controls how compact or wide the presentation is:
|
929 |
+
|
930 |
+
>>> format_timedelta(timedelta(hours=3), format='short', locale='en')
|
931 |
+
u'3 hr'
|
932 |
+
>>> format_timedelta(timedelta(hours=3), format='narrow', locale='en')
|
933 |
+
u'3h'
|
934 |
+
|
935 |
+
:param delta: a ``timedelta`` object representing the time difference to
|
936 |
+
format, or the delta in seconds as an `int` value
|
937 |
+
:param granularity: determines the smallest unit that should be displayed,
|
938 |
+
the value can be one of "year", "month", "week", "day",
|
939 |
+
"hour", "minute" or "second"
|
940 |
+
:param threshold: factor that determines at which point the presentation
|
941 |
+
switches to the next higher unit
|
942 |
+
:param add_direction: if this flag is set to `True` the return value will
|
943 |
+
include directional information. For instance a
|
944 |
+
positive timedelta will include the information about
|
945 |
+
it being in the future, a negative will be information
|
946 |
+
about the value being in the past.
|
947 |
+
:param format: the format, can be "narrow", "short" or "long". (
|
948 |
+
"medium" is deprecated, currently converted to "long" to
|
949 |
+
maintain compatibility)
|
950 |
+
:param locale: a `Locale` object or a locale identifier. Defaults to the system time locale.
|
951 |
+
"""
|
952 |
+
if format not in ('narrow', 'short', 'medium', 'long'):
|
953 |
+
raise TypeError('Format must be one of "narrow", "short" or "long"')
|
954 |
+
if format == 'medium':
|
955 |
+
warnings.warn(
|
956 |
+
'"medium" value for format param of format_timedelta'
|
957 |
+
' is deprecated. Use "long" instead',
|
958 |
+
category=DeprecationWarning,
|
959 |
+
stacklevel=2,
|
960 |
+
)
|
961 |
+
format = 'long'
|
962 |
+
if isinstance(delta, datetime.timedelta):
|
963 |
+
seconds = int((delta.days * 86400) + delta.seconds)
|
964 |
+
else:
|
965 |
+
seconds = delta
|
966 |
+
locale = Locale.parse(locale or LC_TIME)
|
967 |
+
date_fields = locale._data["date_fields"]
|
968 |
+
unit_patterns = locale._data["unit_patterns"]
|
969 |
+
|
970 |
+
def _iter_patterns(a_unit):
|
971 |
+
if add_direction:
|
972 |
+
# Try to find the length variant version first ("year-narrow")
|
973 |
+
# before falling back to the default.
|
974 |
+
unit_rel_patterns = (date_fields.get(f"{a_unit}-{format}") or date_fields[a_unit])
|
975 |
+
if seconds >= 0:
|
976 |
+
yield unit_rel_patterns['future']
|
977 |
+
else:
|
978 |
+
yield unit_rel_patterns['past']
|
979 |
+
a_unit = f"duration-{a_unit}"
|
980 |
+
unit_pats = unit_patterns.get(a_unit, {})
|
981 |
+
yield unit_pats.get(format)
|
982 |
+
# We do not support `<alias>` tags at all while ingesting CLDR data,
|
983 |
+
# so these aliases specified in `root.xml` are hard-coded here:
|
984 |
+
# <unitLength type="long"><alias source="locale" path="../unitLength[@type='short']"/></unitLength>
|
985 |
+
# <unitLength type="narrow"><alias source="locale" path="../unitLength[@type='short']"/></unitLength>
|
986 |
+
if format in ("long", "narrow"):
|
987 |
+
yield unit_pats.get("short")
|
988 |
+
|
989 |
+
for unit, secs_per_unit in TIMEDELTA_UNITS:
|
990 |
+
value = abs(seconds) / secs_per_unit
|
991 |
+
if value >= threshold or unit == granularity:
|
992 |
+
if unit == granularity and value > 0:
|
993 |
+
value = max(1, value)
|
994 |
+
value = int(round(value))
|
995 |
+
plural_form = locale.plural_form(value)
|
996 |
+
pattern = None
|
997 |
+
for patterns in _iter_patterns(unit):
|
998 |
+
if patterns is not None:
|
999 |
+
pattern = patterns.get(plural_form) or patterns.get('other')
|
1000 |
+
if pattern:
|
1001 |
+
break
|
1002 |
+
# This really should not happen
|
1003 |
+
if pattern is None:
|
1004 |
+
return ''
|
1005 |
+
return pattern.replace('{0}', str(value))
|
1006 |
+
|
1007 |
+
return ''
|
1008 |
+
|
1009 |
+
|
1010 |
+
def _format_fallback_interval(
|
1011 |
+
start: _Instant,
|
1012 |
+
end: _Instant,
|
1013 |
+
skeleton: str | None,
|
1014 |
+
tzinfo: datetime.tzinfo | None,
|
1015 |
+
locale: Locale,
|
1016 |
+
) -> str:
|
1017 |
+
if skeleton in locale.datetime_skeletons: # Use the given skeleton
|
1018 |
+
format = lambda dt: format_skeleton(skeleton, dt, tzinfo, locale=locale)
|
1019 |
+
elif all((isinstance(d, datetime.date) and not isinstance(d, datetime.datetime)) for d in (start, end)): # Both are just dates
|
1020 |
+
format = lambda dt: format_date(dt, locale=locale)
|
1021 |
+
elif all((isinstance(d, datetime.time) and not isinstance(d, datetime.date)) for d in (start, end)): # Both are times
|
1022 |
+
format = lambda dt: format_time(dt, tzinfo=tzinfo, locale=locale)
|
1023 |
+
else:
|
1024 |
+
format = lambda dt: format_datetime(dt, tzinfo=tzinfo, locale=locale)
|
1025 |
+
|
1026 |
+
formatted_start = format(start)
|
1027 |
+
formatted_end = format(end)
|
1028 |
+
|
1029 |
+
if formatted_start == formatted_end:
|
1030 |
+
return format(start)
|
1031 |
+
|
1032 |
+
return (
|
1033 |
+
locale.interval_formats.get(None, "{0}-{1}").
|
1034 |
+
replace("{0}", formatted_start).
|
1035 |
+
replace("{1}", formatted_end)
|
1036 |
+
)
|
1037 |
+
|
1038 |
+
|
1039 |
+
def format_interval(
|
1040 |
+
start: _Instant,
|
1041 |
+
end: _Instant,
|
1042 |
+
skeleton: str | None = None,
|
1043 |
+
tzinfo: datetime.tzinfo | None = None,
|
1044 |
+
fuzzy: bool = True,
|
1045 |
+
locale: Locale | str | None = None,
|
1046 |
+
) -> str:
|
1047 |
+
"""
|
1048 |
+
Format an interval between two instants according to the locale's rules.
|
1049 |
+
|
1050 |
+
>>> from datetime import date, time
|
1051 |
+
>>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "yMd", locale="fi")
|
1052 |
+
u'15.\u201317.1.2016'
|
1053 |
+
|
1054 |
+
>>> format_interval(time(12, 12), time(16, 16), "Hm", locale="en_GB")
|
1055 |
+
'12:12\u201316:16'
|
1056 |
+
|
1057 |
+
>>> format_interval(time(5, 12), time(16, 16), "hm", locale="en_US")
|
1058 |
+
'5:12\u202fAM\u2009–\u20094:16\u202fPM'
|
1059 |
+
|
1060 |
+
>>> format_interval(time(16, 18), time(16, 24), "Hm", locale="it")
|
1061 |
+
'16:18\u201316:24'
|
1062 |
+
|
1063 |
+
If the start instant equals the end instant, the interval is formatted like the instant.
|
1064 |
+
|
1065 |
+
>>> format_interval(time(16, 18), time(16, 18), "Hm", locale="it")
|
1066 |
+
'16:18'
|
1067 |
+
|
1068 |
+
Unknown skeletons fall back to "default" formatting.
|
1069 |
+
|
1070 |
+
>>> format_interval(date(2015, 1, 1), date(2017, 1, 1), "wzq", locale="ja")
|
1071 |
+
'2015/01/01\uff5e2017/01/01'
|
1072 |
+
|
1073 |
+
>>> format_interval(time(16, 18), time(16, 24), "xxx", locale="ja")
|
1074 |
+
'16:18:00\uff5e16:24:00'
|
1075 |
+
|
1076 |
+
>>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "xxx", locale="de")
|
1077 |
+
'15.01.2016\u2009–\u200917.01.2016'
|
1078 |
+
|
1079 |
+
:param start: First instant (datetime/date/time)
|
1080 |
+
:param end: Second instant (datetime/date/time)
|
1081 |
+
:param skeleton: The "skeleton format" to use for formatting.
|
1082 |
+
:param tzinfo: tzinfo to use (if none is already attached)
|
1083 |
+
:param fuzzy: If the skeleton is not found, allow choosing a skeleton that's
|
1084 |
+
close enough to it.
|
1085 |
+
:param locale: A locale object or identifier. Defaults to the system time locale.
|
1086 |
+
:return: Formatted interval
|
1087 |
+
"""
|
1088 |
+
locale = Locale.parse(locale or LC_TIME)
|
1089 |
+
|
1090 |
+
# NB: The quote comments below are from the algorithm description in
|
1091 |
+
# https://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats
|
1092 |
+
|
1093 |
+
# > Look for the intervalFormatItem element that matches the "skeleton",
|
1094 |
+
# > starting in the current locale and then following the locale fallback
|
1095 |
+
# > chain up to, but not including root.
|
1096 |
+
|
1097 |
+
interval_formats = locale.interval_formats
|
1098 |
+
|
1099 |
+
if skeleton not in interval_formats or not skeleton:
|
1100 |
+
# > If no match was found from the previous step, check what the closest
|
1101 |
+
# > match is in the fallback locale chain, as in availableFormats. That
|
1102 |
+
# > is, this allows for adjusting the string value field's width,
|
1103 |
+
# > including adjusting between "MMM" and "MMMM", and using different
|
1104 |
+
# > variants of the same field, such as 'v' and 'z'.
|
1105 |
+
if skeleton and fuzzy:
|
1106 |
+
skeleton = match_skeleton(skeleton, interval_formats)
|
1107 |
+
else:
|
1108 |
+
skeleton = None
|
1109 |
+
if not skeleton: # Still no match whatsoever?
|
1110 |
+
# > Otherwise, format the start and end datetime using the fallback pattern.
|
1111 |
+
return _format_fallback_interval(start, end, skeleton, tzinfo, locale)
|
1112 |
+
|
1113 |
+
skel_formats = interval_formats[skeleton]
|
1114 |
+
|
1115 |
+
if start == end:
|
1116 |
+
return format_skeleton(skeleton, start, tzinfo, fuzzy=fuzzy, locale=locale)
|
1117 |
+
|
1118 |
+
start = _ensure_datetime_tzinfo(_get_datetime(start), tzinfo=tzinfo)
|
1119 |
+
end = _ensure_datetime_tzinfo(_get_datetime(end), tzinfo=tzinfo)
|
1120 |
+
|
1121 |
+
start_fmt = DateTimeFormat(start, locale=locale)
|
1122 |
+
end_fmt = DateTimeFormat(end, locale=locale)
|
1123 |
+
|
1124 |
+
# > If a match is found from previous steps, compute the calendar field
|
1125 |
+
# > with the greatest difference between start and end datetime. If there
|
1126 |
+
# > is no difference among any of the fields in the pattern, format as a
|
1127 |
+
# > single date using availableFormats, and return.
|
1128 |
+
|
1129 |
+
for field in PATTERN_CHAR_ORDER: # These are in largest-to-smallest order
|
1130 |
+
if field in skel_formats and start_fmt.extract(field) != end_fmt.extract(field):
|
1131 |
+
# > If there is a match, use the pieces of the corresponding pattern to
|
1132 |
+
# > format the start and end datetime, as above.
|
1133 |
+
return "".join(
|
1134 |
+
parse_pattern(pattern).apply(instant, locale)
|
1135 |
+
for pattern, instant
|
1136 |
+
in zip(skel_formats[field], (start, end))
|
1137 |
+
)
|
1138 |
+
|
1139 |
+
# > Otherwise, format the start and end datetime using the fallback pattern.
|
1140 |
+
|
1141 |
+
return _format_fallback_interval(start, end, skeleton, tzinfo, locale)
|
1142 |
+
|
1143 |
+
|
1144 |
+
def get_period_id(
|
1145 |
+
time: _Instant,
|
1146 |
+
tzinfo: datetime.tzinfo | None = None,
|
1147 |
+
type: Literal['selection'] | None = None,
|
1148 |
+
locale: Locale | str | None = None,
|
1149 |
+
) -> str:
|
1150 |
+
"""
|
1151 |
+
Get the day period ID for a given time.
|
1152 |
+
|
1153 |
+
This ID can be used as a key for the period name dictionary.
|
1154 |
+
|
1155 |
+
>>> from datetime import time
|
1156 |
+
>>> get_period_names(locale="de")[get_period_id(time(7, 42), locale="de")]
|
1157 |
+
u'Morgen'
|
1158 |
+
|
1159 |
+
>>> get_period_id(time(0), locale="en_US")
|
1160 |
+
u'midnight'
|
1161 |
+
|
1162 |
+
>>> get_period_id(time(0), type="selection", locale="en_US")
|
1163 |
+
u'night1'
|
1164 |
+
|
1165 |
+
:param time: The time to inspect.
|
1166 |
+
:param tzinfo: The timezone for the time. See ``format_time``.
|
1167 |
+
:param type: The period type to use. Either "selection" or None.
|
1168 |
+
The selection type is used for selecting among phrases such as
|
1169 |
+
“Your email arrived yesterday evening” or “Your email arrived last night”.
|
1170 |
+
:param locale: the `Locale` object, or a locale string. Defaults to the system time locale.
|
1171 |
+
:return: period ID. Something is always returned -- even if it's just "am" or "pm".
|
1172 |
+
"""
|
1173 |
+
time = _get_time(time, tzinfo)
|
1174 |
+
seconds_past_midnight = int(time.hour * 60 * 60 + time.minute * 60 + time.second)
|
1175 |
+
locale = Locale.parse(locale or LC_TIME)
|
1176 |
+
|
1177 |
+
# The LDML rules state that the rules may not overlap, so iterating in arbitrary
|
1178 |
+
# order should be alright, though `at` periods should be preferred.
|
1179 |
+
rulesets = locale.day_period_rules.get(type, {}).items()
|
1180 |
+
|
1181 |
+
for rule_id, rules in rulesets:
|
1182 |
+
for rule in rules:
|
1183 |
+
if "at" in rule and rule["at"] == seconds_past_midnight:
|
1184 |
+
return rule_id
|
1185 |
+
|
1186 |
+
for rule_id, rules in rulesets:
|
1187 |
+
for rule in rules:
|
1188 |
+
if "from" in rule and "before" in rule:
|
1189 |
+
if rule["from"] < rule["before"]:
|
1190 |
+
if rule["from"] <= seconds_past_midnight < rule["before"]:
|
1191 |
+
return rule_id
|
1192 |
+
else:
|
1193 |
+
# e.g. from="21:00" before="06:00"
|
1194 |
+
if rule["from"] <= seconds_past_midnight < 86400 or \
|
1195 |
+
0 <= seconds_past_midnight < rule["before"]:
|
1196 |
+
return rule_id
|
1197 |
+
|
1198 |
+
start_ok = end_ok = False
|
1199 |
+
|
1200 |
+
if "from" in rule and seconds_past_midnight >= rule["from"]:
|
1201 |
+
start_ok = True
|
1202 |
+
if "to" in rule and seconds_past_midnight <= rule["to"]:
|
1203 |
+
# This rule type does not exist in the present CLDR data;
|
1204 |
+
# excuse the lack of test coverage.
|
1205 |
+
end_ok = True
|
1206 |
+
if "before" in rule and seconds_past_midnight < rule["before"]:
|
1207 |
+
end_ok = True
|
1208 |
+
if "after" in rule:
|
1209 |
+
raise NotImplementedError("'after' is deprecated as of CLDR 29.")
|
1210 |
+
|
1211 |
+
if start_ok and end_ok:
|
1212 |
+
return rule_id
|
1213 |
+
|
1214 |
+
if seconds_past_midnight < 43200:
|
1215 |
+
return "am"
|
1216 |
+
else:
|
1217 |
+
return "pm"
|
1218 |
+
|
1219 |
+
|
1220 |
+
class ParseError(ValueError):
|
1221 |
+
pass
|
1222 |
+
|
1223 |
+
|
1224 |
+
def parse_date(
|
1225 |
+
string: str,
|
1226 |
+
locale: Locale | str | None = None,
|
1227 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
1228 |
+
) -> datetime.date:
|
1229 |
+
"""Parse a date from a string.
|
1230 |
+
|
1231 |
+
If an explicit format is provided, it is used to parse the date.
|
1232 |
+
|
1233 |
+
>>> parse_date('01.04.2004', format='dd.MM.yyyy')
|
1234 |
+
datetime.date(2004, 4, 1)
|
1235 |
+
|
1236 |
+
If no format is given, or if it is one of "full", "long", "medium",
|
1237 |
+
or "short", the function first tries to interpret the string as
|
1238 |
+
ISO-8601 date format and then uses the date format for the locale
|
1239 |
+
as a hint to determine the order in which the date fields appear in
|
1240 |
+
the string.
|
1241 |
+
|
1242 |
+
>>> parse_date('4/1/04', locale='en_US')
|
1243 |
+
datetime.date(2004, 4, 1)
|
1244 |
+
>>> parse_date('01.04.2004', locale='de_DE')
|
1245 |
+
datetime.date(2004, 4, 1)
|
1246 |
+
>>> parse_date('2004-04-01', locale='en_US')
|
1247 |
+
datetime.date(2004, 4, 1)
|
1248 |
+
>>> parse_date('2004-04-01', locale='de_DE')
|
1249 |
+
datetime.date(2004, 4, 1)
|
1250 |
+
>>> parse_date('01.04.04', locale='de_DE', format='short')
|
1251 |
+
datetime.date(2004, 4, 1)
|
1252 |
+
|
1253 |
+
:param string: the string containing the date
|
1254 |
+
:param locale: a `Locale` object or a locale identifier
|
1255 |
+
:param locale: a `Locale` object or a locale identifier. Defaults to the system time locale.
|
1256 |
+
:param format: the format to use, either an explicit date format,
|
1257 |
+
or one of "full", "long", "medium", or "short"
|
1258 |
+
(see ``get_time_format``)
|
1259 |
+
"""
|
1260 |
+
numbers = re.findall(r'(\d+)', string)
|
1261 |
+
if not numbers:
|
1262 |
+
raise ParseError("No numbers were found in input")
|
1263 |
+
|
1264 |
+
use_predefined_format = format in ('full', 'long', 'medium', 'short')
|
1265 |
+
# we try ISO-8601 format first, meaning similar to formats
|
1266 |
+
# extended YYYY-MM-DD or basic YYYYMMDD
|
1267 |
+
iso_alike = re.match(r'^(\d{4})-?([01]\d)-?([0-3]\d)$',
|
1268 |
+
string, flags=re.ASCII) # allow only ASCII digits
|
1269 |
+
if iso_alike and use_predefined_format:
|
1270 |
+
try:
|
1271 |
+
return datetime.date(*map(int, iso_alike.groups()))
|
1272 |
+
except ValueError:
|
1273 |
+
pass # a locale format might fit better, so let's continue
|
1274 |
+
|
1275 |
+
if use_predefined_format:
|
1276 |
+
fmt = get_date_format(format=format, locale=locale)
|
1277 |
+
else:
|
1278 |
+
fmt = parse_pattern(format)
|
1279 |
+
format_str = fmt.pattern.lower()
|
1280 |
+
year_idx = format_str.index('y')
|
1281 |
+
month_idx = format_str.find('m')
|
1282 |
+
if month_idx < 0:
|
1283 |
+
month_idx = format_str.index('l')
|
1284 |
+
day_idx = format_str.index('d')
|
1285 |
+
|
1286 |
+
indexes = sorted([(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')])
|
1287 |
+
indexes = {item[1]: idx for idx, item in enumerate(indexes)}
|
1288 |
+
|
1289 |
+
# FIXME: this currently only supports numbers, but should also support month
|
1290 |
+
# names, both in the requested locale, and english
|
1291 |
+
|
1292 |
+
year = numbers[indexes['Y']]
|
1293 |
+
year = 2000 + int(year) if len(year) == 2 else int(year)
|
1294 |
+
month = int(numbers[indexes['M']])
|
1295 |
+
day = int(numbers[indexes['D']])
|
1296 |
+
if month > 12:
|
1297 |
+
month, day = day, month
|
1298 |
+
return datetime.date(year, month, day)
|
1299 |
+
|
1300 |
+
|
1301 |
+
def parse_time(
|
1302 |
+
string: str,
|
1303 |
+
locale: Locale | str | None = None,
|
1304 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
1305 |
+
) -> datetime.time:
|
1306 |
+
"""Parse a time from a string.
|
1307 |
+
|
1308 |
+
This function uses the time format for the locale as a hint to determine
|
1309 |
+
the order in which the time fields appear in the string.
|
1310 |
+
|
1311 |
+
If an explicit format is provided, the function will use it to parse
|
1312 |
+
the time instead.
|
1313 |
+
|
1314 |
+
>>> parse_time('15:30:00', locale='en_US')
|
1315 |
+
datetime.time(15, 30)
|
1316 |
+
>>> parse_time('15:30:00', format='H:mm:ss')
|
1317 |
+
datetime.time(15, 30)
|
1318 |
+
|
1319 |
+
:param string: the string containing the time
|
1320 |
+
:param locale: a `Locale` object or a locale identifier. Defaults to the system time locale.
|
1321 |
+
:param format: the format to use, either an explicit time format,
|
1322 |
+
or one of "full", "long", "medium", or "short"
|
1323 |
+
(see ``get_time_format``)
|
1324 |
+
:return: the parsed time
|
1325 |
+
:rtype: `time`
|
1326 |
+
"""
|
1327 |
+
numbers = re.findall(r'(\d+)', string)
|
1328 |
+
if not numbers:
|
1329 |
+
raise ParseError("No numbers were found in input")
|
1330 |
+
|
1331 |
+
# TODO: try ISO format first?
|
1332 |
+
if format in ('full', 'long', 'medium', 'short'):
|
1333 |
+
fmt = get_time_format(format=format, locale=locale)
|
1334 |
+
else:
|
1335 |
+
fmt = parse_pattern(format)
|
1336 |
+
format_str = fmt.pattern.lower()
|
1337 |
+
hour_idx = format_str.find('h')
|
1338 |
+
if hour_idx < 0:
|
1339 |
+
hour_idx = format_str.index('k')
|
1340 |
+
min_idx = format_str.index('m')
|
1341 |
+
# format might not contain seconds
|
1342 |
+
if (sec_idx := format_str.find('s')) < 0:
|
1343 |
+
sec_idx = math.inf
|
1344 |
+
|
1345 |
+
indexes = sorted([(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')])
|
1346 |
+
indexes = {item[1]: idx for idx, item in enumerate(indexes)}
|
1347 |
+
|
1348 |
+
# TODO: support time zones
|
1349 |
+
|
1350 |
+
# Check if the format specifies a period to be used;
|
1351 |
+
# if it does, look for 'pm' to figure out an offset.
|
1352 |
+
hour_offset = 0
|
1353 |
+
if 'a' in format_str and 'pm' in string.lower():
|
1354 |
+
hour_offset = 12
|
1355 |
+
|
1356 |
+
# Parse up to three numbers from the string.
|
1357 |
+
minute = second = 0
|
1358 |
+
hour = int(numbers[indexes['H']]) + hour_offset
|
1359 |
+
if len(numbers) > 1:
|
1360 |
+
minute = int(numbers[indexes['M']])
|
1361 |
+
if len(numbers) > 2:
|
1362 |
+
second = int(numbers[indexes['S']])
|
1363 |
+
return datetime.time(hour, minute, second)
|
1364 |
+
|
1365 |
+
|
1366 |
+
class DateTimePattern:
|
1367 |
+
|
1368 |
+
def __init__(self, pattern: str, format: DateTimeFormat):
|
1369 |
+
self.pattern = pattern
|
1370 |
+
self.format = format
|
1371 |
+
|
1372 |
+
def __repr__(self) -> str:
|
1373 |
+
return f"<{type(self).__name__} {self.pattern!r}>"
|
1374 |
+
|
1375 |
+
def __str__(self) -> str:
|
1376 |
+
pat = self.pattern
|
1377 |
+
return pat
|
1378 |
+
|
1379 |
+
def __mod__(self, other: DateTimeFormat) -> str:
|
1380 |
+
if not isinstance(other, DateTimeFormat):
|
1381 |
+
return NotImplemented
|
1382 |
+
return self.format % other
|
1383 |
+
|
1384 |
+
def apply(
|
1385 |
+
self,
|
1386 |
+
datetime: datetime.date | datetime.time,
|
1387 |
+
locale: Locale | str | None,
|
1388 |
+
reference_date: datetime.date | None = None,
|
1389 |
+
) -> str:
|
1390 |
+
return self % DateTimeFormat(datetime, locale, reference_date)
|
1391 |
+
|
1392 |
+
|
1393 |
+
class DateTimeFormat:
|
1394 |
+
|
1395 |
+
def __init__(
|
1396 |
+
self,
|
1397 |
+
value: datetime.date | datetime.time,
|
1398 |
+
locale: Locale | str,
|
1399 |
+
reference_date: datetime.date | None = None,
|
1400 |
+
) -> None:
|
1401 |
+
assert isinstance(value, (datetime.date, datetime.datetime, datetime.time))
|
1402 |
+
if isinstance(value, (datetime.datetime, datetime.time)) and value.tzinfo is None:
|
1403 |
+
value = value.replace(tzinfo=UTC)
|
1404 |
+
self.value = value
|
1405 |
+
self.locale = Locale.parse(locale)
|
1406 |
+
self.reference_date = reference_date
|
1407 |
+
|
1408 |
+
def __getitem__(self, name: str) -> str:
|
1409 |
+
char = name[0]
|
1410 |
+
num = len(name)
|
1411 |
+
if char == 'G':
|
1412 |
+
return self.format_era(char, num)
|
1413 |
+
elif char in ('y', 'Y', 'u'):
|
1414 |
+
return self.format_year(char, num)
|
1415 |
+
elif char in ('Q', 'q'):
|
1416 |
+
return self.format_quarter(char, num)
|
1417 |
+
elif char in ('M', 'L'):
|
1418 |
+
return self.format_month(char, num)
|
1419 |
+
elif char in ('w', 'W'):
|
1420 |
+
return self.format_week(char, num)
|
1421 |
+
elif char == 'd':
|
1422 |
+
return self.format(self.value.day, num)
|
1423 |
+
elif char == 'D':
|
1424 |
+
return self.format_day_of_year(num)
|
1425 |
+
elif char == 'F':
|
1426 |
+
return self.format_day_of_week_in_month()
|
1427 |
+
elif char in ('E', 'e', 'c'):
|
1428 |
+
return self.format_weekday(char, num)
|
1429 |
+
elif char in ('a', 'b', 'B'):
|
1430 |
+
return self.format_period(char, num)
|
1431 |
+
elif char == 'h':
|
1432 |
+
if self.value.hour % 12 == 0:
|
1433 |
+
return self.format(12, num)
|
1434 |
+
else:
|
1435 |
+
return self.format(self.value.hour % 12, num)
|
1436 |
+
elif char == 'H':
|
1437 |
+
return self.format(self.value.hour, num)
|
1438 |
+
elif char == 'K':
|
1439 |
+
return self.format(self.value.hour % 12, num)
|
1440 |
+
elif char == 'k':
|
1441 |
+
if self.value.hour == 0:
|
1442 |
+
return self.format(24, num)
|
1443 |
+
else:
|
1444 |
+
return self.format(self.value.hour, num)
|
1445 |
+
elif char == 'm':
|
1446 |
+
return self.format(self.value.minute, num)
|
1447 |
+
elif char == 's':
|
1448 |
+
return self.format(self.value.second, num)
|
1449 |
+
elif char == 'S':
|
1450 |
+
return self.format_frac_seconds(num)
|
1451 |
+
elif char == 'A':
|
1452 |
+
return self.format_milliseconds_in_day(num)
|
1453 |
+
elif char in ('z', 'Z', 'v', 'V', 'x', 'X', 'O'):
|
1454 |
+
return self.format_timezone(char, num)
|
1455 |
+
else:
|
1456 |
+
raise KeyError(f"Unsupported date/time field {char!r}")
|
1457 |
+
|
1458 |
+
def extract(self, char: str) -> int:
|
1459 |
+
char = str(char)[0]
|
1460 |
+
if char == 'y':
|
1461 |
+
return self.value.year
|
1462 |
+
elif char == 'M':
|
1463 |
+
return self.value.month
|
1464 |
+
elif char == 'd':
|
1465 |
+
return self.value.day
|
1466 |
+
elif char == 'H':
|
1467 |
+
return self.value.hour
|
1468 |
+
elif char == 'h':
|
1469 |
+
return self.value.hour % 12 or 12
|
1470 |
+
elif char == 'm':
|
1471 |
+
return self.value.minute
|
1472 |
+
elif char == 'a':
|
1473 |
+
return int(self.value.hour >= 12) # 0 for am, 1 for pm
|
1474 |
+
else:
|
1475 |
+
raise NotImplementedError(f"Not implemented: extracting {char!r} from {self.value!r}")
|
1476 |
+
|
1477 |
+
def format_era(self, char: str, num: int) -> str:
|
1478 |
+
width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[max(3, num)]
|
1479 |
+
era = int(self.value.year >= 0)
|
1480 |
+
return get_era_names(width, self.locale)[era]
|
1481 |
+
|
1482 |
+
def format_year(self, char: str, num: int) -> str:
|
1483 |
+
value = self.value.year
|
1484 |
+
if char.isupper():
|
1485 |
+
month = self.value.month
|
1486 |
+
if month == 1 and self.value.day < 7 and self.get_week_of_year() >= 52:
|
1487 |
+
value -= 1
|
1488 |
+
elif month == 12 and self.value.day > 25 and self.get_week_of_year() <= 2:
|
1489 |
+
value += 1
|
1490 |
+
year = self.format(value, num)
|
1491 |
+
if num == 2:
|
1492 |
+
year = year[-2:]
|
1493 |
+
return year
|
1494 |
+
|
1495 |
+
def format_quarter(self, char: str, num: int) -> str:
|
1496 |
+
quarter = (self.value.month - 1) // 3 + 1
|
1497 |
+
if num <= 2:
|
1498 |
+
return '%0*d' % (num, quarter)
|
1499 |
+
width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
|
1500 |
+
context = {'Q': 'format', 'q': 'stand-alone'}[char]
|
1501 |
+
return get_quarter_names(width, context, self.locale)[quarter]
|
1502 |
+
|
1503 |
+
def format_month(self, char: str, num: int) -> str:
|
1504 |
+
if num <= 2:
|
1505 |
+
return '%0*d' % (num, self.value.month)
|
1506 |
+
width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
|
1507 |
+
context = {'M': 'format', 'L': 'stand-alone'}[char]
|
1508 |
+
return get_month_names(width, context, self.locale)[self.value.month]
|
1509 |
+
|
1510 |
+
def format_week(self, char: str, num: int) -> str:
|
1511 |
+
if char.islower(): # week of year
|
1512 |
+
week = self.get_week_of_year()
|
1513 |
+
return self.format(week, num)
|
1514 |
+
else: # week of month
|
1515 |
+
week = self.get_week_of_month()
|
1516 |
+
return str(week)
|
1517 |
+
|
1518 |
+
def format_weekday(self, char: str = 'E', num: int = 4) -> str:
|
1519 |
+
"""
|
1520 |
+
Return weekday from parsed datetime according to format pattern.
|
1521 |
+
|
1522 |
+
>>> from datetime import date
|
1523 |
+
>>> format = DateTimeFormat(date(2016, 2, 28), Locale.parse('en_US'))
|
1524 |
+
>>> format.format_weekday()
|
1525 |
+
u'Sunday'
|
1526 |
+
|
1527 |
+
'E': Day of week - Use one through three letters for the abbreviated day name, four for the full (wide) name,
|
1528 |
+
five for the narrow name, or six for the short name.
|
1529 |
+
>>> format.format_weekday('E',2)
|
1530 |
+
u'Sun'
|
1531 |
+
|
1532 |
+
'e': Local day of week. Same as E except adds a numeric value that will depend on the local starting day of the
|
1533 |
+
week, using one or two letters. For this example, Monday is the first day of the week.
|
1534 |
+
>>> format.format_weekday('e',2)
|
1535 |
+
'01'
|
1536 |
+
|
1537 |
+
'c': Stand-Alone local day of week - Use one letter for the local numeric value (same as 'e'), three for the
|
1538 |
+
abbreviated day name, four for the full (wide) name, five for the narrow name, or six for the short name.
|
1539 |
+
>>> format.format_weekday('c',1)
|
1540 |
+
'1'
|
1541 |
+
|
1542 |
+
:param char: pattern format character ('e','E','c')
|
1543 |
+
:param num: count of format character
|
1544 |
+
|
1545 |
+
"""
|
1546 |
+
if num < 3:
|
1547 |
+
if char.islower():
|
1548 |
+
value = 7 - self.locale.first_week_day + self.value.weekday()
|
1549 |
+
return self.format(value % 7 + 1, num)
|
1550 |
+
num = 3
|
1551 |
+
weekday = self.value.weekday()
|
1552 |
+
width = {3: 'abbreviated', 4: 'wide', 5: 'narrow', 6: 'short'}[num]
|
1553 |
+
context = "stand-alone" if char == "c" else "format"
|
1554 |
+
return get_day_names(width, context, self.locale)[weekday]
|
1555 |
+
|
1556 |
+
def format_day_of_year(self, num: int) -> str:
|
1557 |
+
return self.format(self.get_day_of_year(), num)
|
1558 |
+
|
1559 |
+
def format_day_of_week_in_month(self) -> str:
|
1560 |
+
return str((self.value.day - 1) // 7 + 1)
|
1561 |
+
|
1562 |
+
def format_period(self, char: str, num: int) -> str:
|
1563 |
+
"""
|
1564 |
+
Return period from parsed datetime according to format pattern.
|
1565 |
+
|
1566 |
+
>>> from datetime import datetime, time
|
1567 |
+
>>> format = DateTimeFormat(time(13, 42), 'fi_FI')
|
1568 |
+
>>> format.format_period('a', 1)
|
1569 |
+
u'ip.'
|
1570 |
+
>>> format.format_period('b', 1)
|
1571 |
+
u'iltap.'
|
1572 |
+
>>> format.format_period('b', 4)
|
1573 |
+
u'iltapäivä'
|
1574 |
+
>>> format.format_period('B', 4)
|
1575 |
+
u'iltapäivällä'
|
1576 |
+
>>> format.format_period('B', 5)
|
1577 |
+
u'ip.'
|
1578 |
+
|
1579 |
+
>>> format = DateTimeFormat(datetime(2022, 4, 28, 6, 27), 'zh_Hant')
|
1580 |
+
>>> format.format_period('a', 1)
|
1581 |
+
u'上午'
|
1582 |
+
>>> format.format_period('B', 1)
|
1583 |
+
u'清晨'
|
1584 |
+
|
1585 |
+
:param char: pattern format character ('a', 'b', 'B')
|
1586 |
+
:param num: count of format character
|
1587 |
+
|
1588 |
+
"""
|
1589 |
+
widths = [{3: 'abbreviated', 4: 'wide', 5: 'narrow'}[max(3, num)],
|
1590 |
+
'wide', 'narrow', 'abbreviated']
|
1591 |
+
if char == 'a':
|
1592 |
+
period = 'pm' if self.value.hour >= 12 else 'am'
|
1593 |
+
context = 'format'
|
1594 |
+
else:
|
1595 |
+
period = get_period_id(self.value, locale=self.locale)
|
1596 |
+
context = 'format' if char == 'B' else 'stand-alone'
|
1597 |
+
for width in widths:
|
1598 |
+
period_names = get_period_names(context=context, width=width, locale=self.locale)
|
1599 |
+
if period in period_names:
|
1600 |
+
return period_names[period]
|
1601 |
+
raise ValueError(f"Could not format period {period} in {self.locale}")
|
1602 |
+
|
1603 |
+
def format_frac_seconds(self, num: int) -> str:
|
1604 |
+
""" Return fractional seconds.
|
1605 |
+
|
1606 |
+
Rounds the time's microseconds to the precision given by the number \
|
1607 |
+
of digits passed in.
|
1608 |
+
"""
|
1609 |
+
value = self.value.microsecond / 1000000
|
1610 |
+
return self.format(round(value, num) * 10**num, num)
|
1611 |
+
|
1612 |
+
def format_milliseconds_in_day(self, num):
|
1613 |
+
msecs = self.value.microsecond // 1000 + self.value.second * 1000 + \
|
1614 |
+
self.value.minute * 60000 + self.value.hour * 3600000
|
1615 |
+
return self.format(msecs, num)
|
1616 |
+
|
1617 |
+
def format_timezone(self, char: str, num: int) -> str:
|
1618 |
+
width = {3: 'short', 4: 'long', 5: 'iso8601'}[max(3, num)]
|
1619 |
+
|
1620 |
+
# It could be that we only receive a time to format, but also have a
|
1621 |
+
# reference date which is important to distinguish between timezone
|
1622 |
+
# variants (summer/standard time)
|
1623 |
+
value = self.value
|
1624 |
+
if self.reference_date:
|
1625 |
+
value = datetime.datetime.combine(self.reference_date, self.value)
|
1626 |
+
|
1627 |
+
if char == 'z':
|
1628 |
+
return get_timezone_name(value, width, locale=self.locale)
|
1629 |
+
elif char == 'Z':
|
1630 |
+
if num == 5:
|
1631 |
+
return get_timezone_gmt(value, width, locale=self.locale, return_z=True)
|
1632 |
+
return get_timezone_gmt(value, width, locale=self.locale)
|
1633 |
+
elif char == 'O':
|
1634 |
+
if num == 4:
|
1635 |
+
return get_timezone_gmt(value, width, locale=self.locale)
|
1636 |
+
# TODO: To add support for O:1
|
1637 |
+
elif char == 'v':
|
1638 |
+
return get_timezone_name(value.tzinfo, width,
|
1639 |
+
locale=self.locale)
|
1640 |
+
elif char == 'V':
|
1641 |
+
if num == 1:
|
1642 |
+
return get_timezone_name(value.tzinfo, width,
|
1643 |
+
uncommon=True, locale=self.locale)
|
1644 |
+
elif num == 2:
|
1645 |
+
return get_timezone_name(value.tzinfo, locale=self.locale, return_zone=True)
|
1646 |
+
elif num == 3:
|
1647 |
+
return get_timezone_location(value.tzinfo, locale=self.locale, return_city=True)
|
1648 |
+
return get_timezone_location(value.tzinfo, locale=self.locale)
|
1649 |
+
# Included additional elif condition to add support for 'Xx' in timezone format
|
1650 |
+
elif char == 'X':
|
1651 |
+
if num == 1:
|
1652 |
+
return get_timezone_gmt(value, width='iso8601_short', locale=self.locale,
|
1653 |
+
return_z=True)
|
1654 |
+
elif num in (2, 4):
|
1655 |
+
return get_timezone_gmt(value, width='short', locale=self.locale,
|
1656 |
+
return_z=True)
|
1657 |
+
elif num in (3, 5):
|
1658 |
+
return get_timezone_gmt(value, width='iso8601', locale=self.locale,
|
1659 |
+
return_z=True)
|
1660 |
+
elif char == 'x':
|
1661 |
+
if num == 1:
|
1662 |
+
return get_timezone_gmt(value, width='iso8601_short', locale=self.locale)
|
1663 |
+
elif num in (2, 4):
|
1664 |
+
return get_timezone_gmt(value, width='short', locale=self.locale)
|
1665 |
+
elif num in (3, 5):
|
1666 |
+
return get_timezone_gmt(value, width='iso8601', locale=self.locale)
|
1667 |
+
|
1668 |
+
def format(self, value: SupportsInt, length: int) -> str:
|
1669 |
+
return '%0*d' % (length, value)
|
1670 |
+
|
1671 |
+
def get_day_of_year(self, date: datetime.date | None = None) -> int:
|
1672 |
+
if date is None:
|
1673 |
+
date = self.value
|
1674 |
+
return (date - date.replace(month=1, day=1)).days + 1
|
1675 |
+
|
1676 |
+
def get_week_of_year(self) -> int:
|
1677 |
+
"""Return the week of the year."""
|
1678 |
+
day_of_year = self.get_day_of_year(self.value)
|
1679 |
+
week = self.get_week_number(day_of_year)
|
1680 |
+
if week == 0:
|
1681 |
+
date = datetime.date(self.value.year - 1, 12, 31)
|
1682 |
+
week = self.get_week_number(self.get_day_of_year(date),
|
1683 |
+
date.weekday())
|
1684 |
+
elif week > 52:
|
1685 |
+
weekday = datetime.date(self.value.year + 1, 1, 1).weekday()
|
1686 |
+
if self.get_week_number(1, weekday) == 1 and \
|
1687 |
+
32 - (weekday - self.locale.first_week_day) % 7 <= self.value.day:
|
1688 |
+
week = 1
|
1689 |
+
return week
|
1690 |
+
|
1691 |
+
def get_week_of_month(self) -> int:
|
1692 |
+
"""Return the week of the month."""
|
1693 |
+
return self.get_week_number(self.value.day)
|
1694 |
+
|
1695 |
+
def get_week_number(self, day_of_period: int, day_of_week: int | None = None) -> int:
|
1696 |
+
"""Return the number of the week of a day within a period. This may be
|
1697 |
+
the week number in a year or the week number in a month.
|
1698 |
+
|
1699 |
+
Usually this will return a value equal to or greater than 1, but if the
|
1700 |
+
first week of the period is so short that it actually counts as the last
|
1701 |
+
week of the previous period, this function will return 0.
|
1702 |
+
|
1703 |
+
>>> date = datetime.date(2006, 1, 8)
|
1704 |
+
>>> DateTimeFormat(date, 'de_DE').get_week_number(6)
|
1705 |
+
1
|
1706 |
+
>>> DateTimeFormat(date, 'en_US').get_week_number(6)
|
1707 |
+
2
|
1708 |
+
|
1709 |
+
:param day_of_period: the number of the day in the period (usually
|
1710 |
+
either the day of month or the day of year)
|
1711 |
+
:param day_of_week: the week day; if omitted, the week day of the
|
1712 |
+
current date is assumed
|
1713 |
+
"""
|
1714 |
+
if day_of_week is None:
|
1715 |
+
day_of_week = self.value.weekday()
|
1716 |
+
first_day = (day_of_week - self.locale.first_week_day -
|
1717 |
+
day_of_period + 1) % 7
|
1718 |
+
if first_day < 0:
|
1719 |
+
first_day += 7
|
1720 |
+
week_number = (day_of_period + first_day - 1) // 7
|
1721 |
+
if 7 - first_day >= self.locale.min_week_days:
|
1722 |
+
week_number += 1
|
1723 |
+
return week_number
|
1724 |
+
|
1725 |
+
|
1726 |
+
PATTERN_CHARS: dict[str, list[int] | None] = {
|
1727 |
+
'G': [1, 2, 3, 4, 5], # era
|
1728 |
+
'y': None, 'Y': None, 'u': None, # year
|
1729 |
+
'Q': [1, 2, 3, 4, 5], 'q': [1, 2, 3, 4, 5], # quarter
|
1730 |
+
'M': [1, 2, 3, 4, 5], 'L': [1, 2, 3, 4, 5], # month
|
1731 |
+
'w': [1, 2], 'W': [1], # week
|
1732 |
+
'd': [1, 2], 'D': [1, 2, 3], 'F': [1], 'g': None, # day
|
1733 |
+
'E': [1, 2, 3, 4, 5, 6], 'e': [1, 2, 3, 4, 5, 6], 'c': [1, 3, 4, 5, 6], # week day
|
1734 |
+
'a': [1, 2, 3, 4, 5], 'b': [1, 2, 3, 4, 5], 'B': [1, 2, 3, 4, 5], # period
|
1735 |
+
'h': [1, 2], 'H': [1, 2], 'K': [1, 2], 'k': [1, 2], # hour
|
1736 |
+
'm': [1, 2], # minute
|
1737 |
+
's': [1, 2], 'S': None, 'A': None, # second
|
1738 |
+
'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4, 5], 'O': [1, 4], 'v': [1, 4], # zone
|
1739 |
+
'V': [1, 2, 3, 4], 'x': [1, 2, 3, 4, 5], 'X': [1, 2, 3, 4, 5], # zone
|
1740 |
+
}
|
1741 |
+
|
1742 |
+
#: The pattern characters declared in the Date Field Symbol Table
|
1743 |
+
#: (https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table)
|
1744 |
+
#: in order of decreasing magnitude.
|
1745 |
+
PATTERN_CHAR_ORDER = "GyYuUQqMLlwWdDFgEecabBChHKkjJmsSAzZOvVXx"
|
1746 |
+
|
1747 |
+
|
1748 |
+
def parse_pattern(pattern: str | DateTimePattern) -> DateTimePattern:
|
1749 |
+
"""Parse date, time, and datetime format patterns.
|
1750 |
+
|
1751 |
+
>>> parse_pattern("MMMMd").format
|
1752 |
+
u'%(MMMM)s%(d)s'
|
1753 |
+
>>> parse_pattern("MMM d, yyyy").format
|
1754 |
+
u'%(MMM)s %(d)s, %(yyyy)s'
|
1755 |
+
|
1756 |
+
Pattern can contain literal strings in single quotes:
|
1757 |
+
|
1758 |
+
>>> parse_pattern("H:mm' Uhr 'z").format
|
1759 |
+
u'%(H)s:%(mm)s Uhr %(z)s'
|
1760 |
+
|
1761 |
+
An actual single quote can be used by using two adjacent single quote
|
1762 |
+
characters:
|
1763 |
+
|
1764 |
+
>>> parse_pattern("hh' o''clock'").format
|
1765 |
+
u"%(hh)s o'clock"
|
1766 |
+
|
1767 |
+
:param pattern: the formatting pattern to parse
|
1768 |
+
"""
|
1769 |
+
if isinstance(pattern, DateTimePattern):
|
1770 |
+
return pattern
|
1771 |
+
return _cached_parse_pattern(pattern)
|
1772 |
+
|
1773 |
+
|
1774 |
+
@lru_cache(maxsize=1024)
|
1775 |
+
def _cached_parse_pattern(pattern: str) -> DateTimePattern:
|
1776 |
+
result = []
|
1777 |
+
|
1778 |
+
for tok_type, tok_value in tokenize_pattern(pattern):
|
1779 |
+
if tok_type == "chars":
|
1780 |
+
result.append(tok_value.replace('%', '%%'))
|
1781 |
+
elif tok_type == "field":
|
1782 |
+
fieldchar, fieldnum = tok_value
|
1783 |
+
limit = PATTERN_CHARS[fieldchar]
|
1784 |
+
if limit and fieldnum not in limit:
|
1785 |
+
raise ValueError(f"Invalid length for field: {fieldchar * fieldnum!r}")
|
1786 |
+
result.append('%%(%s)s' % (fieldchar * fieldnum))
|
1787 |
+
else:
|
1788 |
+
raise NotImplementedError(f"Unknown token type: {tok_type}")
|
1789 |
+
return DateTimePattern(pattern, ''.join(result))
|
1790 |
+
|
1791 |
+
|
1792 |
+
def tokenize_pattern(pattern: str) -> list[tuple[str, str | tuple[str, int]]]:
|
1793 |
+
"""
|
1794 |
+
Tokenize date format patterns.
|
1795 |
+
|
1796 |
+
Returns a list of (token_type, token_value) tuples.
|
1797 |
+
|
1798 |
+
``token_type`` may be either "chars" or "field".
|
1799 |
+
|
1800 |
+
For "chars" tokens, the value is the literal value.
|
1801 |
+
|
1802 |
+
For "field" tokens, the value is a tuple of (field character, repetition count).
|
1803 |
+
|
1804 |
+
:param pattern: Pattern string
|
1805 |
+
:type pattern: str
|
1806 |
+
:rtype: list[tuple]
|
1807 |
+
"""
|
1808 |
+
result = []
|
1809 |
+
quotebuf = None
|
1810 |
+
charbuf = []
|
1811 |
+
fieldchar = ['']
|
1812 |
+
fieldnum = [0]
|
1813 |
+
|
1814 |
+
def append_chars():
|
1815 |
+
result.append(('chars', ''.join(charbuf).replace('\0', "'")))
|
1816 |
+
del charbuf[:]
|
1817 |
+
|
1818 |
+
def append_field():
|
1819 |
+
result.append(('field', (fieldchar[0], fieldnum[0])))
|
1820 |
+
fieldchar[0] = ''
|
1821 |
+
fieldnum[0] = 0
|
1822 |
+
|
1823 |
+
for char in pattern.replace("''", '\0'):
|
1824 |
+
if quotebuf is None:
|
1825 |
+
if char == "'": # quote started
|
1826 |
+
if fieldchar[0]:
|
1827 |
+
append_field()
|
1828 |
+
elif charbuf:
|
1829 |
+
append_chars()
|
1830 |
+
quotebuf = []
|
1831 |
+
elif char in PATTERN_CHARS:
|
1832 |
+
if charbuf:
|
1833 |
+
append_chars()
|
1834 |
+
if char == fieldchar[0]:
|
1835 |
+
fieldnum[0] += 1
|
1836 |
+
else:
|
1837 |
+
if fieldchar[0]:
|
1838 |
+
append_field()
|
1839 |
+
fieldchar[0] = char
|
1840 |
+
fieldnum[0] = 1
|
1841 |
+
else:
|
1842 |
+
if fieldchar[0]:
|
1843 |
+
append_field()
|
1844 |
+
charbuf.append(char)
|
1845 |
+
|
1846 |
+
elif quotebuf is not None:
|
1847 |
+
if char == "'": # end of quote
|
1848 |
+
charbuf.extend(quotebuf)
|
1849 |
+
quotebuf = None
|
1850 |
+
else: # inside quote
|
1851 |
+
quotebuf.append(char)
|
1852 |
+
|
1853 |
+
if fieldchar[0]:
|
1854 |
+
append_field()
|
1855 |
+
elif charbuf:
|
1856 |
+
append_chars()
|
1857 |
+
|
1858 |
+
return result
|
1859 |
+
|
1860 |
+
|
1861 |
+
def untokenize_pattern(tokens: Iterable[tuple[str, str | tuple[str, int]]]) -> str:
|
1862 |
+
"""
|
1863 |
+
Turn a date format pattern token stream back into a string.
|
1864 |
+
|
1865 |
+
This is the reverse operation of ``tokenize_pattern``.
|
1866 |
+
|
1867 |
+
:type tokens: Iterable[tuple]
|
1868 |
+
:rtype: str
|
1869 |
+
"""
|
1870 |
+
output = []
|
1871 |
+
for tok_type, tok_value in tokens:
|
1872 |
+
if tok_type == "field":
|
1873 |
+
output.append(tok_value[0] * tok_value[1])
|
1874 |
+
elif tok_type == "chars":
|
1875 |
+
if not any(ch in PATTERN_CHARS for ch in tok_value): # No need to quote
|
1876 |
+
output.append(tok_value)
|
1877 |
+
else:
|
1878 |
+
output.append("'%s'" % tok_value.replace("'", "''"))
|
1879 |
+
return "".join(output)
|
1880 |
+
|
1881 |
+
|
1882 |
+
def split_interval_pattern(pattern: str) -> list[str]:
|
1883 |
+
"""
|
1884 |
+
Split an interval-describing datetime pattern into multiple pieces.
|
1885 |
+
|
1886 |
+
> The pattern is then designed to be broken up into two pieces by determining the first repeating field.
|
1887 |
+
- https://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats
|
1888 |
+
|
1889 |
+
>>> split_interval_pattern(u'E d.M. \u2013 E d.M.')
|
1890 |
+
[u'E d.M. \u2013 ', 'E d.M.']
|
1891 |
+
>>> split_interval_pattern("Y 'text' Y 'more text'")
|
1892 |
+
["Y 'text '", "Y 'more text'"]
|
1893 |
+
>>> split_interval_pattern(u"E, MMM d \u2013 E")
|
1894 |
+
[u'E, MMM d \u2013 ', u'E']
|
1895 |
+
>>> split_interval_pattern("MMM d")
|
1896 |
+
['MMM d']
|
1897 |
+
>>> split_interval_pattern("y G")
|
1898 |
+
['y G']
|
1899 |
+
>>> split_interval_pattern(u"MMM d \u2013 d")
|
1900 |
+
[u'MMM d \u2013 ', u'd']
|
1901 |
+
|
1902 |
+
:param pattern: Interval pattern string
|
1903 |
+
:return: list of "subpatterns"
|
1904 |
+
"""
|
1905 |
+
|
1906 |
+
seen_fields = set()
|
1907 |
+
parts = [[]]
|
1908 |
+
|
1909 |
+
for tok_type, tok_value in tokenize_pattern(pattern):
|
1910 |
+
if tok_type == "field":
|
1911 |
+
if tok_value[0] in seen_fields: # Repeated field
|
1912 |
+
parts.append([])
|
1913 |
+
seen_fields.clear()
|
1914 |
+
seen_fields.add(tok_value[0])
|
1915 |
+
parts[-1].append((tok_type, tok_value))
|
1916 |
+
|
1917 |
+
return [untokenize_pattern(tokens) for tokens in parts]
|
1918 |
+
|
1919 |
+
|
1920 |
+
def match_skeleton(skeleton: str, options: Iterable[str], allow_different_fields: bool = False) -> str | None:
|
1921 |
+
"""
|
1922 |
+
Find the closest match for the given datetime skeleton among the options given.
|
1923 |
+
|
1924 |
+
This uses the rules outlined in the TR35 document.
|
1925 |
+
|
1926 |
+
>>> match_skeleton('yMMd', ('yMd', 'yMMMd'))
|
1927 |
+
'yMd'
|
1928 |
+
|
1929 |
+
>>> match_skeleton('yMMd', ('jyMMd',), allow_different_fields=True)
|
1930 |
+
'jyMMd'
|
1931 |
+
|
1932 |
+
>>> match_skeleton('yMMd', ('qyMMd',), allow_different_fields=False)
|
1933 |
+
|
1934 |
+
>>> match_skeleton('hmz', ('hmv',))
|
1935 |
+
'hmv'
|
1936 |
+
|
1937 |
+
:param skeleton: The skeleton to match
|
1938 |
+
:type skeleton: str
|
1939 |
+
:param options: An iterable of other skeletons to match against
|
1940 |
+
:type options: Iterable[str]
|
1941 |
+
:param allow_different_fields: Whether to allow a match that uses different fields
|
1942 |
+
than the skeleton requested.
|
1943 |
+
:type allow_different_fields: bool
|
1944 |
+
|
1945 |
+
:return: The closest skeleton match, or if no match was found, None.
|
1946 |
+
:rtype: str|None
|
1947 |
+
"""
|
1948 |
+
|
1949 |
+
# TODO: maybe implement pattern expansion?
|
1950 |
+
|
1951 |
+
# Based on the implementation in
|
1952 |
+
# https://github.com/unicode-org/icu/blob/main/icu4j/main/core/src/main/java/com/ibm/icu/text/DateIntervalInfo.java
|
1953 |
+
|
1954 |
+
# Filter out falsy values and sort for stability; when `interval_formats` is passed in, there may be a None key.
|
1955 |
+
options = sorted(option for option in options if option)
|
1956 |
+
|
1957 |
+
if 'z' in skeleton and not any('z' in option for option in options):
|
1958 |
+
skeleton = skeleton.replace('z', 'v')
|
1959 |
+
if 'k' in skeleton and not any('k' in option for option in options):
|
1960 |
+
skeleton = skeleton.replace('k', 'H')
|
1961 |
+
if 'K' in skeleton and not any('K' in option for option in options):
|
1962 |
+
skeleton = skeleton.replace('K', 'h')
|
1963 |
+
if 'a' in skeleton and not any('a' in option for option in options):
|
1964 |
+
skeleton = skeleton.replace('a', '')
|
1965 |
+
if 'b' in skeleton and not any('b' in option for option in options):
|
1966 |
+
skeleton = skeleton.replace('b', '')
|
1967 |
+
|
1968 |
+
get_input_field_width = dict(t[1] for t in tokenize_pattern(skeleton) if t[0] == "field").get
|
1969 |
+
best_skeleton = None
|
1970 |
+
best_distance = None
|
1971 |
+
for option in options:
|
1972 |
+
get_opt_field_width = dict(t[1] for t in tokenize_pattern(option) if t[0] == "field").get
|
1973 |
+
distance = 0
|
1974 |
+
for field in PATTERN_CHARS:
|
1975 |
+
input_width = get_input_field_width(field, 0)
|
1976 |
+
opt_width = get_opt_field_width(field, 0)
|
1977 |
+
if input_width == opt_width:
|
1978 |
+
continue
|
1979 |
+
if opt_width == 0 or input_width == 0:
|
1980 |
+
if not allow_different_fields: # This one is not okay
|
1981 |
+
option = None
|
1982 |
+
break
|
1983 |
+
distance += 0x1000 # Magic weight constant for "entirely different fields"
|
1984 |
+
elif field == 'M' and ((input_width > 2 and opt_width <= 2) or (input_width <= 2 and opt_width > 2)):
|
1985 |
+
distance += 0x100 # Magic weight for "text turns into a number"
|
1986 |
+
else:
|
1987 |
+
distance += abs(input_width - opt_width)
|
1988 |
+
|
1989 |
+
if not option: # We lost the option along the way (probably due to "allow_different_fields")
|
1990 |
+
continue
|
1991 |
+
|
1992 |
+
if not best_skeleton or distance < best_distance:
|
1993 |
+
best_skeleton = option
|
1994 |
+
best_distance = distance
|
1995 |
+
|
1996 |
+
if distance == 0: # Found a perfect match!
|
1997 |
+
break
|
1998 |
+
|
1999 |
+
return best_skeleton
|
lib/python3.10/site-packages/babel/languages.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from babel.core import get_global
|
4 |
+
|
5 |
+
|
6 |
+
def get_official_languages(territory: str, regional: bool = False, de_facto: bool = False) -> tuple[str, ...]:
|
7 |
+
"""
|
8 |
+
Get the official language(s) for the given territory.
|
9 |
+
|
10 |
+
The language codes, if any are known, are returned in order of descending popularity.
|
11 |
+
|
12 |
+
If the `regional` flag is set, then languages which are regionally official are also returned.
|
13 |
+
|
14 |
+
If the `de_facto` flag is set, then languages which are "de facto" official are also returned.
|
15 |
+
|
16 |
+
.. warning:: Note that the data is as up to date as the current version of the CLDR used
|
17 |
+
by Babel. If you need scientifically accurate information, use another source!
|
18 |
+
|
19 |
+
:param territory: Territory code
|
20 |
+
:type territory: str
|
21 |
+
:param regional: Whether to return regionally official languages too
|
22 |
+
:type regional: bool
|
23 |
+
:param de_facto: Whether to return de-facto official languages too
|
24 |
+
:type de_facto: bool
|
25 |
+
:return: Tuple of language codes
|
26 |
+
:rtype: tuple[str]
|
27 |
+
"""
|
28 |
+
|
29 |
+
territory = str(territory).upper()
|
30 |
+
allowed_stati = {"official"}
|
31 |
+
if regional:
|
32 |
+
allowed_stati.add("official_regional")
|
33 |
+
if de_facto:
|
34 |
+
allowed_stati.add("de_facto_official")
|
35 |
+
|
36 |
+
languages = get_global("territory_languages").get(territory, {})
|
37 |
+
pairs = [
|
38 |
+
(info['population_percent'], language)
|
39 |
+
for language, info in languages.items()
|
40 |
+
if info.get('official_status') in allowed_stati
|
41 |
+
]
|
42 |
+
pairs.sort(reverse=True)
|
43 |
+
return tuple(lang for _, lang in pairs)
|
44 |
+
|
45 |
+
|
46 |
+
def get_territory_language_info(territory: str) -> dict[str, dict[str, float | str | None]]:
|
47 |
+
"""
|
48 |
+
Get a dictionary of language information for a territory.
|
49 |
+
|
50 |
+
The dictionary is keyed by language code; the values are dicts with more information.
|
51 |
+
|
52 |
+
The following keys are currently known for the values:
|
53 |
+
|
54 |
+
* `population_percent`: The percentage of the territory's population speaking the
|
55 |
+
language.
|
56 |
+
* `official_status`: An optional string describing the officiality status of the language.
|
57 |
+
Known values are "official", "official_regional" and "de_facto_official".
|
58 |
+
|
59 |
+
.. warning:: Note that the data is as up to date as the current version of the CLDR used
|
60 |
+
by Babel. If you need scientifically accurate information, use another source!
|
61 |
+
|
62 |
+
.. note:: Note that the format of the dict returned may change between Babel versions.
|
63 |
+
|
64 |
+
See https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html
|
65 |
+
|
66 |
+
:param territory: Territory code
|
67 |
+
:type territory: str
|
68 |
+
:return: Language information dictionary
|
69 |
+
:rtype: dict[str, dict]
|
70 |
+
"""
|
71 |
+
territory = str(territory).upper()
|
72 |
+
return get_global("territory_languages").get(territory, {}).copy()
|
lib/python3.10/site-packages/babel/lists.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
babel.lists
|
3 |
+
~~~~~~~~~~~
|
4 |
+
|
5 |
+
Locale dependent formatting of lists.
|
6 |
+
|
7 |
+
The default locale for the functions in this module is determined by the
|
8 |
+
following environment variables, in that order:
|
9 |
+
|
10 |
+
* ``LC_ALL``, and
|
11 |
+
* ``LANG``
|
12 |
+
|
13 |
+
:copyright: (c) 2015-2025 by the Babel Team.
|
14 |
+
:license: BSD, see LICENSE for more details.
|
15 |
+
"""
|
16 |
+
from __future__ import annotations
|
17 |
+
|
18 |
+
import warnings
|
19 |
+
from collections.abc import Sequence
|
20 |
+
from typing import Literal
|
21 |
+
|
22 |
+
from babel.core import Locale, default_locale
|
23 |
+
|
24 |
+
_DEFAULT_LOCALE = default_locale() # TODO(3.0): Remove this.
|
25 |
+
|
26 |
+
|
27 |
+
def __getattr__(name):
|
28 |
+
if name == "DEFAULT_LOCALE":
|
29 |
+
warnings.warn(
|
30 |
+
"The babel.lists.DEFAULT_LOCALE constant is deprecated and will be removed.",
|
31 |
+
DeprecationWarning,
|
32 |
+
stacklevel=2,
|
33 |
+
)
|
34 |
+
return _DEFAULT_LOCALE
|
35 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
36 |
+
|
37 |
+
|
38 |
+
def format_list(
|
39 |
+
lst: Sequence[str],
|
40 |
+
style: Literal['standard', 'standard-short', 'or', 'or-short', 'unit', 'unit-short', 'unit-narrow'] = 'standard',
|
41 |
+
locale: Locale | str | None = None,
|
42 |
+
) -> str:
|
43 |
+
"""
|
44 |
+
Format the items in `lst` as a list.
|
45 |
+
|
46 |
+
>>> format_list(['apples', 'oranges', 'pears'], locale='en')
|
47 |
+
u'apples, oranges, and pears'
|
48 |
+
>>> format_list(['apples', 'oranges', 'pears'], locale='zh')
|
49 |
+
u'apples\u3001oranges\u548cpears'
|
50 |
+
>>> format_list(['omena', 'peruna', 'aplari'], style='or', locale='fi')
|
51 |
+
u'omena, peruna tai aplari'
|
52 |
+
|
53 |
+
Not all styles are necessarily available in all locales.
|
54 |
+
The function will attempt to fall back to replacement styles according to the rules
|
55 |
+
set forth in the CLDR root XML file, and raise a ValueError if no suitable replacement
|
56 |
+
can be found.
|
57 |
+
|
58 |
+
The following text is verbatim from the Unicode TR35-49 spec [1].
|
59 |
+
|
60 |
+
* standard:
|
61 |
+
A typical 'and' list for arbitrary placeholders.
|
62 |
+
eg. "January, February, and March"
|
63 |
+
* standard-short:
|
64 |
+
A short version of an 'and' list, suitable for use with short or abbreviated placeholder values.
|
65 |
+
eg. "Jan., Feb., and Mar."
|
66 |
+
* or:
|
67 |
+
A typical 'or' list for arbitrary placeholders.
|
68 |
+
eg. "January, February, or March"
|
69 |
+
* or-short:
|
70 |
+
A short version of an 'or' list.
|
71 |
+
eg. "Jan., Feb., or Mar."
|
72 |
+
* unit:
|
73 |
+
A list suitable for wide units.
|
74 |
+
eg. "3 feet, 7 inches"
|
75 |
+
* unit-short:
|
76 |
+
A list suitable for short units
|
77 |
+
eg. "3 ft, 7 in"
|
78 |
+
* unit-narrow:
|
79 |
+
A list suitable for narrow units, where space on the screen is very limited.
|
80 |
+
eg. "3′ 7″"
|
81 |
+
|
82 |
+
[1]: https://www.unicode.org/reports/tr35/tr35-49/tr35-general.html#ListPatterns
|
83 |
+
|
84 |
+
:param lst: a sequence of items to format in to a list
|
85 |
+
:param style: the style to format the list with. See above for description.
|
86 |
+
:param locale: the locale. Defaults to the system locale.
|
87 |
+
"""
|
88 |
+
locale = Locale.parse(locale or _DEFAULT_LOCALE)
|
89 |
+
if not lst:
|
90 |
+
return ''
|
91 |
+
if len(lst) == 1:
|
92 |
+
return lst[0]
|
93 |
+
|
94 |
+
patterns = _resolve_list_style(locale, style)
|
95 |
+
|
96 |
+
if len(lst) == 2 and '2' in patterns:
|
97 |
+
return patterns['2'].format(*lst)
|
98 |
+
|
99 |
+
result = patterns['start'].format(lst[0], lst[1])
|
100 |
+
for elem in lst[2:-1]:
|
101 |
+
result = patterns['middle'].format(result, elem)
|
102 |
+
result = patterns['end'].format(result, lst[-1])
|
103 |
+
|
104 |
+
return result
|
105 |
+
|
106 |
+
|
107 |
+
# Based on CLDR 45's root.xml file's `<alias>`es.
|
108 |
+
# The root file defines both `standard` and `or`,
|
109 |
+
# so they're always available.
|
110 |
+
# TODO: It would likely be better to use the
|
111 |
+
# babel.localedata.Alias mechanism for this,
|
112 |
+
# but I'm not quite sure how it's supposed to
|
113 |
+
# work with inheritance and data in the root.
|
114 |
+
_style_fallbacks = {
|
115 |
+
"or-narrow": ["or-short", "or"],
|
116 |
+
"or-short": ["or"],
|
117 |
+
"standard-narrow": ["standard-short", "standard"],
|
118 |
+
"standard-short": ["standard"],
|
119 |
+
"unit": ["unit-short", "standard"],
|
120 |
+
"unit-narrow": ["unit-short", "unit", "standard"],
|
121 |
+
"unit-short": ["standard"],
|
122 |
+
}
|
123 |
+
|
124 |
+
|
125 |
+
def _resolve_list_style(locale: Locale, style: str):
|
126 |
+
for style in (style, *(_style_fallbacks.get(style, []))): # noqa: B020
|
127 |
+
if style in locale.list_patterns:
|
128 |
+
return locale.list_patterns[style]
|
129 |
+
raise ValueError(
|
130 |
+
f"Locale {locale} does not support list formatting style {style!r} "
|
131 |
+
f"(supported are {sorted(locale.list_patterns)})",
|
132 |
+
)
|
lib/python3.10/site-packages/babel/locale-data/chr_US.dat
ADDED
Binary file (654 Bytes). View file
|
|
lib/python3.10/site-packages/babel/locale-data/kok_Deva.dat
ADDED
Binary file (693 Bytes). View file
|
|
lib/python3.10/site-packages/babel/locale-data/nr.dat
ADDED
Binary file (2.17 kB). View file
|
|
lib/python3.10/site-packages/babel/localedata.py
ADDED
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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` class, which uses this module under the hood, provides a
|
8 |
+
more convenient interface for accessing the locale data.
|
9 |
+
|
10 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
11 |
+
:license: BSD, see LICENSE for more details.
|
12 |
+
"""
|
13 |
+
|
14 |
+
from __future__ import annotations
|
15 |
+
|
16 |
+
import os
|
17 |
+
import pickle
|
18 |
+
import re
|
19 |
+
import sys
|
20 |
+
import threading
|
21 |
+
from collections import abc
|
22 |
+
from collections.abc import Iterator, Mapping, MutableMapping
|
23 |
+
from functools import lru_cache
|
24 |
+
from itertools import chain
|
25 |
+
from typing import Any
|
26 |
+
|
27 |
+
_cache: dict[str, Any] = {}
|
28 |
+
_cache_lock = threading.RLock()
|
29 |
+
_dirname = os.path.join(os.path.dirname(__file__), 'locale-data')
|
30 |
+
_windows_reserved_name_re = re.compile("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$", re.I)
|
31 |
+
|
32 |
+
|
33 |
+
def normalize_locale(name: str) -> str | None:
|
34 |
+
"""Normalize a locale ID by stripping spaces and apply proper casing.
|
35 |
+
|
36 |
+
Returns the normalized locale ID string or `None` if the ID is not
|
37 |
+
recognized.
|
38 |
+
"""
|
39 |
+
if not name or not isinstance(name, str):
|
40 |
+
return None
|
41 |
+
name = name.strip().lower()
|
42 |
+
for locale_id in chain.from_iterable([_cache, locale_identifiers()]):
|
43 |
+
if name == locale_id.lower():
|
44 |
+
return locale_id
|
45 |
+
|
46 |
+
|
47 |
+
def resolve_locale_filename(name: os.PathLike[str] | str) -> str:
|
48 |
+
"""
|
49 |
+
Resolve a locale identifier to a `.dat` path on disk.
|
50 |
+
"""
|
51 |
+
|
52 |
+
# Clean up any possible relative paths.
|
53 |
+
name = os.path.basename(name)
|
54 |
+
|
55 |
+
# Ensure we're not left with one of the Windows reserved names.
|
56 |
+
if sys.platform == "win32" and _windows_reserved_name_re.match(os.path.splitext(name)[0]):
|
57 |
+
raise ValueError(f"Name {name} is invalid on Windows")
|
58 |
+
|
59 |
+
# Build the path.
|
60 |
+
return os.path.join(_dirname, f"{name}.dat")
|
61 |
+
|
62 |
+
|
63 |
+
def exists(name: str) -> bool:
|
64 |
+
"""Check whether locale data is available for the given locale.
|
65 |
+
|
66 |
+
Returns `True` if it exists, `False` otherwise.
|
67 |
+
|
68 |
+
:param name: the locale identifier string
|
69 |
+
"""
|
70 |
+
if not name or not isinstance(name, str):
|
71 |
+
return False
|
72 |
+
if name in _cache:
|
73 |
+
return True
|
74 |
+
file_found = os.path.exists(resolve_locale_filename(name))
|
75 |
+
return True if file_found else bool(normalize_locale(name))
|
76 |
+
|
77 |
+
|
78 |
+
@lru_cache(maxsize=None)
|
79 |
+
def locale_identifiers() -> list[str]:
|
80 |
+
"""Return a list of all locale identifiers for which locale data is
|
81 |
+
available.
|
82 |
+
|
83 |
+
This data is cached after the first invocation.
|
84 |
+
You can clear the cache by calling `locale_identifiers.cache_clear()`.
|
85 |
+
|
86 |
+
.. versionadded:: 0.8.1
|
87 |
+
|
88 |
+
:return: a list of locale identifiers (strings)
|
89 |
+
"""
|
90 |
+
return [
|
91 |
+
stem
|
92 |
+
for stem, extension in
|
93 |
+
(os.path.splitext(filename) for filename in os.listdir(_dirname))
|
94 |
+
if extension == '.dat' and stem != 'root'
|
95 |
+
]
|
96 |
+
|
97 |
+
|
98 |
+
def _is_non_likely_script(name: str) -> bool:
|
99 |
+
"""Return whether the locale is of the form ``lang_Script``,
|
100 |
+
and the script is not the likely script for the language.
|
101 |
+
|
102 |
+
This implements the behavior of the ``nonlikelyScript`` value of the
|
103 |
+
``localRules`` attribute for parent locales added in CLDR 45.
|
104 |
+
"""
|
105 |
+
from babel.core import get_global, parse_locale
|
106 |
+
|
107 |
+
try:
|
108 |
+
lang, territory, script, variant, *rest = parse_locale(name)
|
109 |
+
except ValueError:
|
110 |
+
return False
|
111 |
+
|
112 |
+
if lang and script and not territory and not variant and not rest:
|
113 |
+
likely_subtag = get_global('likely_subtags').get(lang)
|
114 |
+
_, _, likely_script, *_ = parse_locale(likely_subtag)
|
115 |
+
return script != likely_script
|
116 |
+
return False
|
117 |
+
|
118 |
+
|
119 |
+
def load(name: os.PathLike[str] | str, merge_inherited: bool = True) -> dict[str, Any]:
|
120 |
+
"""Load the locale data for the given locale.
|
121 |
+
|
122 |
+
The locale data is a dictionary that contains much of the data defined by
|
123 |
+
the Common Locale Data Repository (CLDR). This data is stored as a
|
124 |
+
collection of pickle files inside the ``babel`` package.
|
125 |
+
|
126 |
+
>>> d = load('en_US')
|
127 |
+
>>> d['languages']['sv']
|
128 |
+
u'Swedish'
|
129 |
+
|
130 |
+
Note that the results are cached, and subsequent requests for the same
|
131 |
+
locale return the same dictionary:
|
132 |
+
|
133 |
+
>>> d1 = load('en_US')
|
134 |
+
>>> d2 = load('en_US')
|
135 |
+
>>> d1 is d2
|
136 |
+
True
|
137 |
+
|
138 |
+
:param name: the locale identifier string (or "root")
|
139 |
+
:param merge_inherited: whether the inherited data should be merged into
|
140 |
+
the data of the requested locale
|
141 |
+
:raise `IOError`: if no locale data file is found for the given locale
|
142 |
+
identifier, or one of the locales it inherits from
|
143 |
+
"""
|
144 |
+
name = os.path.basename(name)
|
145 |
+
_cache_lock.acquire()
|
146 |
+
try:
|
147 |
+
data = _cache.get(name)
|
148 |
+
if not data:
|
149 |
+
# Load inherited data
|
150 |
+
if name == 'root' or not merge_inherited:
|
151 |
+
data = {}
|
152 |
+
else:
|
153 |
+
from babel.core import get_global
|
154 |
+
parent = get_global('parent_exceptions').get(name)
|
155 |
+
if not parent:
|
156 |
+
if _is_non_likely_script(name):
|
157 |
+
parent = 'root'
|
158 |
+
else:
|
159 |
+
parts = name.split('_')
|
160 |
+
parent = "root" if len(parts) == 1 else "_".join(parts[:-1])
|
161 |
+
data = load(parent).copy()
|
162 |
+
filename = resolve_locale_filename(name)
|
163 |
+
with open(filename, 'rb') as fileobj:
|
164 |
+
if name != 'root' and merge_inherited:
|
165 |
+
merge(data, pickle.load(fileobj))
|
166 |
+
else:
|
167 |
+
data = pickle.load(fileobj)
|
168 |
+
_cache[name] = data
|
169 |
+
return data
|
170 |
+
finally:
|
171 |
+
_cache_lock.release()
|
172 |
+
|
173 |
+
|
174 |
+
def merge(dict1: MutableMapping[Any, Any], dict2: Mapping[Any, Any]) -> None:
|
175 |
+
"""Merge the data from `dict2` into the `dict1` dictionary, making copies
|
176 |
+
of nested dictionaries.
|
177 |
+
|
178 |
+
>>> d = {1: 'foo', 3: 'baz'}
|
179 |
+
>>> merge(d, {1: 'Foo', 2: 'Bar'})
|
180 |
+
>>> sorted(d.items())
|
181 |
+
[(1, 'Foo'), (2, 'Bar'), (3, 'baz')]
|
182 |
+
|
183 |
+
:param dict1: the dictionary to merge into
|
184 |
+
:param dict2: the dictionary containing the data that should be merged
|
185 |
+
"""
|
186 |
+
for key, val2 in dict2.items():
|
187 |
+
if val2 is not None:
|
188 |
+
val1 = dict1.get(key)
|
189 |
+
if isinstance(val2, dict):
|
190 |
+
if val1 is None:
|
191 |
+
val1 = {}
|
192 |
+
if isinstance(val1, Alias):
|
193 |
+
val1 = (val1, val2)
|
194 |
+
elif isinstance(val1, tuple):
|
195 |
+
alias, others = val1
|
196 |
+
others = others.copy()
|
197 |
+
merge(others, val2)
|
198 |
+
val1 = (alias, others)
|
199 |
+
else:
|
200 |
+
val1 = val1.copy()
|
201 |
+
merge(val1, val2)
|
202 |
+
else:
|
203 |
+
val1 = val2
|
204 |
+
dict1[key] = val1
|
205 |
+
|
206 |
+
|
207 |
+
class Alias:
|
208 |
+
"""Representation of an alias in the locale data.
|
209 |
+
|
210 |
+
An alias is a value that refers to some other part of the locale data,
|
211 |
+
as specified by the `keys`.
|
212 |
+
"""
|
213 |
+
|
214 |
+
def __init__(self, keys: tuple[str, ...]) -> None:
|
215 |
+
self.keys = tuple(keys)
|
216 |
+
|
217 |
+
def __repr__(self) -> str:
|
218 |
+
return f"<{type(self).__name__} {self.keys!r}>"
|
219 |
+
|
220 |
+
def resolve(self, data: Mapping[str | int | None, Any]) -> Mapping[str | int | None, Any]:
|
221 |
+
"""Resolve the alias based on the given data.
|
222 |
+
|
223 |
+
This is done recursively, so if one alias resolves to a second alias,
|
224 |
+
that second alias will also be resolved.
|
225 |
+
|
226 |
+
:param data: the locale data
|
227 |
+
:type data: `dict`
|
228 |
+
"""
|
229 |
+
base = data
|
230 |
+
for key in self.keys:
|
231 |
+
data = data[key]
|
232 |
+
if isinstance(data, Alias):
|
233 |
+
data = data.resolve(base)
|
234 |
+
elif isinstance(data, tuple):
|
235 |
+
alias, others = data
|
236 |
+
data = alias.resolve(base)
|
237 |
+
return data
|
238 |
+
|
239 |
+
|
240 |
+
class LocaleDataDict(abc.MutableMapping):
|
241 |
+
"""Dictionary wrapper that automatically resolves aliases to the actual
|
242 |
+
values.
|
243 |
+
"""
|
244 |
+
|
245 |
+
def __init__(self, data: MutableMapping[str | int | None, Any], base: Mapping[str | int | None, Any] | None = None):
|
246 |
+
self._data = data
|
247 |
+
if base is None:
|
248 |
+
base = data
|
249 |
+
self.base = base
|
250 |
+
|
251 |
+
def __len__(self) -> int:
|
252 |
+
return len(self._data)
|
253 |
+
|
254 |
+
def __iter__(self) -> Iterator[str | int | None]:
|
255 |
+
return iter(self._data)
|
256 |
+
|
257 |
+
def __getitem__(self, key: str | int | None) -> Any:
|
258 |
+
orig = val = self._data[key]
|
259 |
+
if isinstance(val, Alias): # resolve an alias
|
260 |
+
val = val.resolve(self.base)
|
261 |
+
if isinstance(val, tuple): # Merge a partial dict with an alias
|
262 |
+
alias, others = val
|
263 |
+
val = alias.resolve(self.base).copy()
|
264 |
+
merge(val, others)
|
265 |
+
if isinstance(val, dict): # Return a nested alias-resolving dict
|
266 |
+
val = LocaleDataDict(val, base=self.base)
|
267 |
+
if val is not orig:
|
268 |
+
self._data[key] = val
|
269 |
+
return val
|
270 |
+
|
271 |
+
def __setitem__(self, key: str | int | None, value: Any) -> None:
|
272 |
+
self._data[key] = value
|
273 |
+
|
274 |
+
def __delitem__(self, key: str | int | None) -> None:
|
275 |
+
del self._data[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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
babel.numbers
|
3 |
+
~~~~~~~~~~~~~
|
4 |
+
|
5 |
+
Locale dependent formatting and parsing of numeric data.
|
6 |
+
|
7 |
+
The default locale for the functions in this module is determined by the
|
8 |
+
following environment variables, in that order:
|
9 |
+
|
10 |
+
* ``LC_MONETARY`` for currency related functions,
|
11 |
+
* ``LC_NUMERIC``, and
|
12 |
+
* ``LC_ALL``, and
|
13 |
+
* ``LANG``
|
14 |
+
|
15 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
16 |
+
:license: BSD, see LICENSE for more details.
|
17 |
+
"""
|
18 |
+
# TODO:
|
19 |
+
# Padding and rounding increments in pattern:
|
20 |
+
# - https://www.unicode.org/reports/tr35/ (Appendix G.6)
|
21 |
+
from __future__ import annotations
|
22 |
+
|
23 |
+
import datetime
|
24 |
+
import decimal
|
25 |
+
import re
|
26 |
+
import warnings
|
27 |
+
from typing import Any, Literal, cast, overload
|
28 |
+
|
29 |
+
from babel.core import Locale, default_locale, get_global
|
30 |
+
from babel.localedata import LocaleDataDict
|
31 |
+
|
32 |
+
LC_MONETARY = default_locale(('LC_MONETARY', 'LC_NUMERIC'))
|
33 |
+
LC_NUMERIC = default_locale('LC_NUMERIC')
|
34 |
+
|
35 |
+
|
36 |
+
class UnknownCurrencyError(Exception):
|
37 |
+
"""Exception thrown when a currency is requested for which no data is available.
|
38 |
+
"""
|
39 |
+
|
40 |
+
def __init__(self, identifier: str) -> None:
|
41 |
+
"""Create the exception.
|
42 |
+
:param identifier: the identifier string of the unsupported currency
|
43 |
+
"""
|
44 |
+
Exception.__init__(self, f"Unknown currency {identifier!r}.")
|
45 |
+
|
46 |
+
#: The identifier of the locale that could not be found.
|
47 |
+
self.identifier = identifier
|
48 |
+
|
49 |
+
|
50 |
+
def list_currencies(locale: Locale | str | None = None) -> set[str]:
|
51 |
+
""" Return a `set` of normalized currency codes.
|
52 |
+
|
53 |
+
.. versionadded:: 2.5.0
|
54 |
+
|
55 |
+
:param locale: filters returned currency codes by the provided locale.
|
56 |
+
Expected to be a locale instance or code. If no locale is
|
57 |
+
provided, returns the list of all currencies from all
|
58 |
+
locales.
|
59 |
+
"""
|
60 |
+
# Get locale-scoped currencies.
|
61 |
+
if locale:
|
62 |
+
return set(Locale.parse(locale).currencies)
|
63 |
+
return set(get_global('all_currencies'))
|
64 |
+
|
65 |
+
|
66 |
+
def validate_currency(currency: str, locale: Locale | str | None = None) -> None:
|
67 |
+
""" Check the currency code is recognized by Babel.
|
68 |
+
|
69 |
+
Accepts a ``locale`` parameter for fined-grained validation, working as
|
70 |
+
the one defined above in ``list_currencies()`` method.
|
71 |
+
|
72 |
+
Raises a `UnknownCurrencyError` exception if the currency is unknown to Babel.
|
73 |
+
"""
|
74 |
+
if currency not in list_currencies(locale):
|
75 |
+
raise UnknownCurrencyError(currency)
|
76 |
+
|
77 |
+
|
78 |
+
def is_currency(currency: str, locale: Locale | str | None = None) -> bool:
|
79 |
+
""" Returns `True` only if a currency is recognized by Babel.
|
80 |
+
|
81 |
+
This method always return a Boolean and never raise.
|
82 |
+
"""
|
83 |
+
if not currency or not isinstance(currency, str):
|
84 |
+
return False
|
85 |
+
try:
|
86 |
+
validate_currency(currency, locale)
|
87 |
+
except UnknownCurrencyError:
|
88 |
+
return False
|
89 |
+
return True
|
90 |
+
|
91 |
+
|
92 |
+
def normalize_currency(currency: str, locale: Locale | str | None = None) -> str | None:
|
93 |
+
"""Returns the normalized identifier of any currency code.
|
94 |
+
|
95 |
+
Accepts a ``locale`` parameter for fined-grained validation, working as
|
96 |
+
the one defined above in ``list_currencies()`` method.
|
97 |
+
|
98 |
+
Returns None if the currency is unknown to Babel.
|
99 |
+
"""
|
100 |
+
if isinstance(currency, str):
|
101 |
+
currency = currency.upper()
|
102 |
+
if not is_currency(currency, locale):
|
103 |
+
return None
|
104 |
+
return currency
|
105 |
+
|
106 |
+
|
107 |
+
def get_currency_name(
|
108 |
+
currency: str,
|
109 |
+
count: float | decimal.Decimal | None = None,
|
110 |
+
locale: Locale | str | None = None,
|
111 |
+
) -> str:
|
112 |
+
"""Return the name used by the locale for the specified currency.
|
113 |
+
|
114 |
+
>>> get_currency_name('USD', locale='en_US')
|
115 |
+
u'US Dollar'
|
116 |
+
|
117 |
+
.. versionadded:: 0.9.4
|
118 |
+
|
119 |
+
:param currency: the currency code.
|
120 |
+
:param count: the optional count. If provided the currency name
|
121 |
+
will be pluralized to that number if possible.
|
122 |
+
:param locale: the `Locale` object or locale identifier.
|
123 |
+
Defaults to the system currency locale or numeric locale.
|
124 |
+
"""
|
125 |
+
loc = Locale.parse(locale or LC_MONETARY)
|
126 |
+
if count is not None:
|
127 |
+
try:
|
128 |
+
plural_form = loc.plural_form(count)
|
129 |
+
except (OverflowError, ValueError):
|
130 |
+
plural_form = 'other'
|
131 |
+
plural_names = loc._data['currency_names_plural']
|
132 |
+
if currency in plural_names:
|
133 |
+
currency_plural_names = plural_names[currency]
|
134 |
+
if plural_form in currency_plural_names:
|
135 |
+
return currency_plural_names[plural_form]
|
136 |
+
if 'other' in currency_plural_names:
|
137 |
+
return currency_plural_names['other']
|
138 |
+
return loc.currencies.get(currency, currency)
|
139 |
+
|
140 |
+
|
141 |
+
def get_currency_symbol(currency: str, locale: Locale | str | None = None) -> str:
|
142 |
+
"""Return the symbol used by the locale for the specified currency.
|
143 |
+
|
144 |
+
>>> get_currency_symbol('USD', locale='en_US')
|
145 |
+
u'$'
|
146 |
+
|
147 |
+
:param currency: the currency code.
|
148 |
+
:param locale: the `Locale` object or locale identifier.
|
149 |
+
Defaults to the system currency locale or numeric locale.
|
150 |
+
"""
|
151 |
+
return Locale.parse(locale or LC_MONETARY).currency_symbols.get(currency, currency)
|
152 |
+
|
153 |
+
|
154 |
+
def get_currency_precision(currency: str) -> int:
|
155 |
+
"""Return currency's precision.
|
156 |
+
|
157 |
+
Precision is the number of decimals found after the decimal point in the
|
158 |
+
currency's format pattern.
|
159 |
+
|
160 |
+
.. versionadded:: 2.5.0
|
161 |
+
|
162 |
+
:param currency: the currency code.
|
163 |
+
"""
|
164 |
+
precisions = get_global('currency_fractions')
|
165 |
+
return precisions.get(currency, precisions['DEFAULT'])[0]
|
166 |
+
|
167 |
+
|
168 |
+
def get_currency_unit_pattern(
|
169 |
+
currency: str, # TODO: unused?!
|
170 |
+
count: float | decimal.Decimal | None = None,
|
171 |
+
locale: Locale | str | None = None,
|
172 |
+
) -> str:
|
173 |
+
"""
|
174 |
+
Return the unit pattern used for long display of a currency value
|
175 |
+
for a given locale.
|
176 |
+
This is a string containing ``{0}`` where the numeric part
|
177 |
+
should be substituted and ``{1}`` where the currency long display
|
178 |
+
name should be substituted.
|
179 |
+
|
180 |
+
>>> get_currency_unit_pattern('USD', locale='en_US', count=10)
|
181 |
+
u'{0} {1}'
|
182 |
+
|
183 |
+
.. versionadded:: 2.7.0
|
184 |
+
|
185 |
+
:param currency: the currency code.
|
186 |
+
:param count: the optional count. If provided the unit
|
187 |
+
pattern for that number will be returned.
|
188 |
+
:param locale: the `Locale` object or locale identifier.
|
189 |
+
Defaults to the system currency locale or numeric locale.
|
190 |
+
"""
|
191 |
+
loc = Locale.parse(locale or LC_MONETARY)
|
192 |
+
if count is not None:
|
193 |
+
plural_form = loc.plural_form(count)
|
194 |
+
try:
|
195 |
+
return loc._data['currency_unit_patterns'][plural_form]
|
196 |
+
except LookupError:
|
197 |
+
# Fall back to 'other'
|
198 |
+
pass
|
199 |
+
|
200 |
+
return loc._data['currency_unit_patterns']['other']
|
201 |
+
|
202 |
+
|
203 |
+
@overload
|
204 |
+
def get_territory_currencies(
|
205 |
+
territory: str,
|
206 |
+
start_date: datetime.date | None = ...,
|
207 |
+
end_date: datetime.date | None = ...,
|
208 |
+
tender: bool = ...,
|
209 |
+
non_tender: bool = ...,
|
210 |
+
include_details: Literal[False] = ...,
|
211 |
+
) -> list[str]:
|
212 |
+
... # pragma: no cover
|
213 |
+
|
214 |
+
|
215 |
+
@overload
|
216 |
+
def get_territory_currencies(
|
217 |
+
territory: str,
|
218 |
+
start_date: datetime.date | None = ...,
|
219 |
+
end_date: datetime.date | None = ...,
|
220 |
+
tender: bool = ...,
|
221 |
+
non_tender: bool = ...,
|
222 |
+
include_details: Literal[True] = ...,
|
223 |
+
) -> list[dict[str, Any]]:
|
224 |
+
... # pragma: no cover
|
225 |
+
|
226 |
+
|
227 |
+
def get_territory_currencies(
|
228 |
+
territory: str,
|
229 |
+
start_date: datetime.date | None = None,
|
230 |
+
end_date: datetime.date | None = None,
|
231 |
+
tender: bool = True,
|
232 |
+
non_tender: bool = False,
|
233 |
+
include_details: bool = False,
|
234 |
+
) -> list[str] | list[dict[str, Any]]:
|
235 |
+
"""Returns the list of currencies for the given territory that are valid for
|
236 |
+
the given date range. In addition to that the currency database
|
237 |
+
distinguishes between tender and non-tender currencies. By default only
|
238 |
+
tender currencies are returned.
|
239 |
+
|
240 |
+
The return value is a list of all currencies roughly ordered by the time
|
241 |
+
of when the currency became active. The longer the currency is being in
|
242 |
+
use the more to the left of the list it will be.
|
243 |
+
|
244 |
+
The start date defaults to today. If no end date is given it will be the
|
245 |
+
same as the start date. Otherwise a range can be defined. For instance
|
246 |
+
this can be used to find the currencies in use in Austria between 1995 and
|
247 |
+
2011:
|
248 |
+
|
249 |
+
>>> from datetime import date
|
250 |
+
>>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
|
251 |
+
['ATS', 'EUR']
|
252 |
+
|
253 |
+
Likewise it's also possible to find all the currencies in use on a
|
254 |
+
single date:
|
255 |
+
|
256 |
+
>>> get_territory_currencies('AT', date(1995, 1, 1))
|
257 |
+
['ATS']
|
258 |
+
>>> get_territory_currencies('AT', date(2011, 1, 1))
|
259 |
+
['EUR']
|
260 |
+
|
261 |
+
By default the return value only includes tender currencies. This
|
262 |
+
however can be changed:
|
263 |
+
|
264 |
+
>>> get_territory_currencies('US')
|
265 |
+
['USD']
|
266 |
+
>>> get_territory_currencies('US', tender=False, non_tender=True,
|
267 |
+
... start_date=date(2014, 1, 1))
|
268 |
+
['USN', 'USS']
|
269 |
+
|
270 |
+
.. versionadded:: 2.0
|
271 |
+
|
272 |
+
:param territory: the name of the territory to find the currency for.
|
273 |
+
:param start_date: the start date. If not given today is assumed.
|
274 |
+
:param end_date: the end date. If not given the start date is assumed.
|
275 |
+
:param tender: controls whether tender currencies should be included.
|
276 |
+
:param non_tender: controls whether non-tender currencies should be
|
277 |
+
included.
|
278 |
+
:param include_details: if set to `True`, instead of returning currency
|
279 |
+
codes the return value will be dictionaries
|
280 |
+
with detail information. In that case each
|
281 |
+
dictionary will have the keys ``'currency'``,
|
282 |
+
``'from'``, ``'to'``, and ``'tender'``.
|
283 |
+
"""
|
284 |
+
currencies = get_global('territory_currencies')
|
285 |
+
if start_date is None:
|
286 |
+
start_date = datetime.date.today()
|
287 |
+
elif isinstance(start_date, datetime.datetime):
|
288 |
+
start_date = start_date.date()
|
289 |
+
if end_date is None:
|
290 |
+
end_date = start_date
|
291 |
+
elif isinstance(end_date, datetime.datetime):
|
292 |
+
end_date = end_date.date()
|
293 |
+
|
294 |
+
curs = currencies.get(territory.upper(), ())
|
295 |
+
# TODO: validate that the territory exists
|
296 |
+
|
297 |
+
def _is_active(start, end):
|
298 |
+
return (start is None or start <= end_date) and \
|
299 |
+
(end is None or end >= start_date)
|
300 |
+
|
301 |
+
result = []
|
302 |
+
for currency_code, start, end, is_tender in curs:
|
303 |
+
if start:
|
304 |
+
start = datetime.date(*start)
|
305 |
+
if end:
|
306 |
+
end = datetime.date(*end)
|
307 |
+
if ((is_tender and tender) or
|
308 |
+
(not is_tender and non_tender)) and _is_active(start, end):
|
309 |
+
if include_details:
|
310 |
+
result.append({
|
311 |
+
'currency': currency_code,
|
312 |
+
'from': start,
|
313 |
+
'to': end,
|
314 |
+
'tender': is_tender,
|
315 |
+
})
|
316 |
+
else:
|
317 |
+
result.append(currency_code)
|
318 |
+
|
319 |
+
return result
|
320 |
+
|
321 |
+
|
322 |
+
def _get_numbering_system(locale: Locale, numbering_system: Literal["default"] | str = "latn") -> str:
|
323 |
+
if numbering_system == "default":
|
324 |
+
return locale.default_numbering_system
|
325 |
+
else:
|
326 |
+
return numbering_system
|
327 |
+
|
328 |
+
|
329 |
+
def _get_number_symbols(
|
330 |
+
locale: Locale,
|
331 |
+
*,
|
332 |
+
numbering_system: Literal["default"] | str = "latn",
|
333 |
+
) -> LocaleDataDict:
|
334 |
+
numbering_system = _get_numbering_system(locale, numbering_system)
|
335 |
+
try:
|
336 |
+
return locale.number_symbols[numbering_system]
|
337 |
+
except KeyError as error:
|
338 |
+
raise UnsupportedNumberingSystemError(f"Unknown numbering system {numbering_system} for Locale {locale}.") from error
|
339 |
+
|
340 |
+
|
341 |
+
class UnsupportedNumberingSystemError(Exception):
|
342 |
+
"""Exception thrown when an unsupported numbering system is requested for the given Locale."""
|
343 |
+
pass
|
344 |
+
|
345 |
+
|
346 |
+
def get_decimal_symbol(
|
347 |
+
locale: Locale | str | None = None,
|
348 |
+
*,
|
349 |
+
numbering_system: Literal["default"] | str = "latn",
|
350 |
+
) -> str:
|
351 |
+
"""Return the symbol used by the locale to separate decimal fractions.
|
352 |
+
|
353 |
+
>>> get_decimal_symbol('en_US')
|
354 |
+
u'.'
|
355 |
+
>>> get_decimal_symbol('ar_EG', numbering_system='default')
|
356 |
+
u'٫'
|
357 |
+
>>> get_decimal_symbol('ar_EG', numbering_system='latn')
|
358 |
+
u'.'
|
359 |
+
|
360 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
361 |
+
:param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
|
362 |
+
The special value "default" will use the default numbering system of the locale.
|
363 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
364 |
+
"""
|
365 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
366 |
+
return _get_number_symbols(locale, numbering_system=numbering_system).get('decimal', '.')
|
367 |
+
|
368 |
+
|
369 |
+
def get_plus_sign_symbol(
|
370 |
+
locale: Locale | str | None = None,
|
371 |
+
*,
|
372 |
+
numbering_system: Literal["default"] | str = "latn",
|
373 |
+
) -> str:
|
374 |
+
"""Return the plus sign symbol used by the current locale.
|
375 |
+
|
376 |
+
>>> get_plus_sign_symbol('en_US')
|
377 |
+
u'+'
|
378 |
+
>>> get_plus_sign_symbol('ar_EG', numbering_system='default')
|
379 |
+
u'\u061c+'
|
380 |
+
>>> get_plus_sign_symbol('ar_EG', numbering_system='latn')
|
381 |
+
u'\u200e+'
|
382 |
+
|
383 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
384 |
+
:param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
|
385 |
+
The special value "default" will use the default numbering system of the locale.
|
386 |
+
:raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
|
387 |
+
"""
|
388 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
389 |
+
return _get_number_symbols(locale, numbering_system=numbering_system).get('plusSign', '+')
|
390 |
+
|
391 |
+
|
392 |
+
def get_minus_sign_symbol(
|
393 |
+
locale: Locale | str | None = None,
|
394 |
+
*,
|
395 |
+
numbering_system: Literal["default"] | str = "latn",
|
396 |
+
) -> str:
|
397 |
+
"""Return the plus sign symbol used by the current locale.
|
398 |
+
|
399 |
+
>>> get_minus_sign_symbol('en_US')
|
400 |
+
u'-'
|
401 |
+
>>> get_minus_sign_symbol('ar_EG', numbering_system='default')
|
402 |
+
u'\u061c-'
|
403 |
+
>>> get_minus_sign_symbol('ar_EG', numbering_system='latn')
|
404 |
+
u'\u200e-'
|
405 |
+
|
406 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
407 |
+
:param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
|
408 |
+
The special value "default" will use the default numbering system of the locale.
|
409 |
+
:raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
|
410 |
+
"""
|
411 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
412 |
+
return _get_number_symbols(locale, numbering_system=numbering_system).get('minusSign', '-')
|
413 |
+
|
414 |
+
|
415 |
+
def get_exponential_symbol(
|
416 |
+
locale: Locale | str | None = None,
|
417 |
+
*,
|
418 |
+
numbering_system: Literal["default"] | str = "latn",
|
419 |
+
) -> str:
|
420 |
+
"""Return the symbol used by the locale to separate mantissa and exponent.
|
421 |
+
|
422 |
+
>>> get_exponential_symbol('en_US')
|
423 |
+
u'E'
|
424 |
+
>>> get_exponential_symbol('ar_EG', numbering_system='default')
|
425 |
+
u'أس'
|
426 |
+
>>> get_exponential_symbol('ar_EG', numbering_system='latn')
|
427 |
+
u'E'
|
428 |
+
|
429 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
430 |
+
:param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
|
431 |
+
The special value "default" will use the default numbering system of the locale.
|
432 |
+
:raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
|
433 |
+
"""
|
434 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
435 |
+
return _get_number_symbols(locale, numbering_system=numbering_system).get('exponential', 'E')
|
436 |
+
|
437 |
+
|
438 |
+
def get_group_symbol(
|
439 |
+
locale: Locale | str | None = None,
|
440 |
+
*,
|
441 |
+
numbering_system: Literal["default"] | str = "latn",
|
442 |
+
) -> str:
|
443 |
+
"""Return the symbol used by the locale to separate groups of thousands.
|
444 |
+
|
445 |
+
>>> get_group_symbol('en_US')
|
446 |
+
u','
|
447 |
+
>>> get_group_symbol('ar_EG', numbering_system='default')
|
448 |
+
u'٬'
|
449 |
+
>>> get_group_symbol('ar_EG', numbering_system='latn')
|
450 |
+
u','
|
451 |
+
|
452 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
453 |
+
:param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
|
454 |
+
The special value "default" will use the default numbering system of the locale.
|
455 |
+
:raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
|
456 |
+
"""
|
457 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
458 |
+
return _get_number_symbols(locale, numbering_system=numbering_system).get('group', ',')
|
459 |
+
|
460 |
+
|
461 |
+
def get_infinity_symbol(
|
462 |
+
locale: Locale | str | None = None,
|
463 |
+
*,
|
464 |
+
numbering_system: Literal["default"] | str = "latn",
|
465 |
+
) -> str:
|
466 |
+
"""Return the symbol used by the locale to represent infinity.
|
467 |
+
|
468 |
+
>>> get_infinity_symbol('en_US')
|
469 |
+
u'∞'
|
470 |
+
>>> get_infinity_symbol('ar_EG', numbering_system='default')
|
471 |
+
u'∞'
|
472 |
+
>>> get_infinity_symbol('ar_EG', numbering_system='latn')
|
473 |
+
u'∞'
|
474 |
+
|
475 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
476 |
+
:param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
|
477 |
+
The special value "default" will use the default numbering system of the locale.
|
478 |
+
:raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
|
479 |
+
"""
|
480 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
481 |
+
return _get_number_symbols(locale, numbering_system=numbering_system).get('infinity', '∞')
|
482 |
+
|
483 |
+
|
484 |
+
def format_number(number: float | decimal.Decimal | str, locale: Locale | str | None = None) -> str:
|
485 |
+
"""Return the given number formatted for a specific locale.
|
486 |
+
|
487 |
+
>>> format_number(1099, locale='en_US') # doctest: +SKIP
|
488 |
+
u'1,099'
|
489 |
+
>>> format_number(1099, locale='de_DE') # doctest: +SKIP
|
490 |
+
u'1.099'
|
491 |
+
|
492 |
+
.. deprecated:: 2.6.0
|
493 |
+
|
494 |
+
Use babel.numbers.format_decimal() instead.
|
495 |
+
|
496 |
+
:param number: the number to format
|
497 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
498 |
+
|
499 |
+
|
500 |
+
"""
|
501 |
+
warnings.warn('Use babel.numbers.format_decimal() instead.', DeprecationWarning, stacklevel=2)
|
502 |
+
return format_decimal(number, locale=locale)
|
503 |
+
|
504 |
+
|
505 |
+
def get_decimal_precision(number: decimal.Decimal) -> int:
|
506 |
+
"""Return maximum precision of a decimal instance's fractional part.
|
507 |
+
|
508 |
+
Precision is extracted from the fractional part only.
|
509 |
+
"""
|
510 |
+
# Copied from: https://github.com/mahmoud/boltons/pull/59
|
511 |
+
assert isinstance(number, decimal.Decimal)
|
512 |
+
decimal_tuple = number.normalize().as_tuple()
|
513 |
+
# Note: DecimalTuple.exponent can be 'n' (qNaN), 'N' (sNaN), or 'F' (Infinity)
|
514 |
+
if not isinstance(decimal_tuple.exponent, int) or decimal_tuple.exponent >= 0:
|
515 |
+
return 0
|
516 |
+
return abs(decimal_tuple.exponent)
|
517 |
+
|
518 |
+
|
519 |
+
def get_decimal_quantum(precision: int | decimal.Decimal) -> decimal.Decimal:
|
520 |
+
"""Return minimal quantum of a number, as defined by precision."""
|
521 |
+
assert isinstance(precision, (int, decimal.Decimal))
|
522 |
+
return decimal.Decimal(10) ** (-precision)
|
523 |
+
|
524 |
+
|
525 |
+
def format_decimal(
|
526 |
+
number: float | decimal.Decimal | str,
|
527 |
+
format: str | NumberPattern | None = None,
|
528 |
+
locale: Locale | str | None = None,
|
529 |
+
decimal_quantization: bool = True,
|
530 |
+
group_separator: bool = True,
|
531 |
+
*,
|
532 |
+
numbering_system: Literal["default"] | str = "latn",
|
533 |
+
) -> str:
|
534 |
+
"""Return the given decimal number formatted for a specific locale.
|
535 |
+
|
536 |
+
>>> format_decimal(1.2345, locale='en_US')
|
537 |
+
u'1.234'
|
538 |
+
>>> format_decimal(1.2346, locale='en_US')
|
539 |
+
u'1.235'
|
540 |
+
>>> format_decimal(-1.2346, locale='en_US')
|
541 |
+
u'-1.235'
|
542 |
+
>>> format_decimal(1.2345, locale='sv_SE')
|
543 |
+
u'1,234'
|
544 |
+
>>> format_decimal(1.2345, locale='de')
|
545 |
+
u'1,234'
|
546 |
+
>>> format_decimal(1.2345, locale='ar_EG', numbering_system='default')
|
547 |
+
u'1٫234'
|
548 |
+
>>> format_decimal(1.2345, locale='ar_EG', numbering_system='latn')
|
549 |
+
u'1.234'
|
550 |
+
|
551 |
+
The appropriate thousands grouping and the decimal separator are used for
|
552 |
+
each locale:
|
553 |
+
|
554 |
+
>>> format_decimal(12345.5, locale='en_US')
|
555 |
+
u'12,345.5'
|
556 |
+
|
557 |
+
By default the locale is allowed to truncate and round a high-precision
|
558 |
+
number by forcing its format pattern onto the decimal part. You can bypass
|
559 |
+
this behavior with the `decimal_quantization` parameter:
|
560 |
+
|
561 |
+
>>> format_decimal(1.2346, locale='en_US')
|
562 |
+
u'1.235'
|
563 |
+
>>> format_decimal(1.2346, locale='en_US', decimal_quantization=False)
|
564 |
+
u'1.2346'
|
565 |
+
>>> format_decimal(12345.67, locale='fr_CA', group_separator=False)
|
566 |
+
u'12345,67'
|
567 |
+
>>> format_decimal(12345.67, locale='en_US', group_separator=True)
|
568 |
+
u'12,345.67'
|
569 |
+
|
570 |
+
:param number: the number to format
|
571 |
+
:param format:
|
572 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
573 |
+
:param decimal_quantization: Truncate and round high-precision numbers to
|
574 |
+
the format pattern. Defaults to `True`.
|
575 |
+
:param group_separator: Boolean to switch group separator on/off in a locale's
|
576 |
+
number format.
|
577 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
578 |
+
The special value "default" will use the default numbering system of the locale.
|
579 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
580 |
+
"""
|
581 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
582 |
+
if format is None:
|
583 |
+
format = locale.decimal_formats[format]
|
584 |
+
pattern = parse_pattern(format)
|
585 |
+
return pattern.apply(
|
586 |
+
number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator, numbering_system=numbering_system)
|
587 |
+
|
588 |
+
|
589 |
+
def format_compact_decimal(
|
590 |
+
number: float | decimal.Decimal | str,
|
591 |
+
*,
|
592 |
+
format_type: Literal["short", "long"] = "short",
|
593 |
+
locale: Locale | str | None = None,
|
594 |
+
fraction_digits: int = 0,
|
595 |
+
numbering_system: Literal["default"] | str = "latn",
|
596 |
+
) -> str:
|
597 |
+
"""Return the given decimal number formatted for a specific locale in compact form.
|
598 |
+
|
599 |
+
>>> format_compact_decimal(12345, format_type="short", locale='en_US')
|
600 |
+
u'12K'
|
601 |
+
>>> format_compact_decimal(12345, format_type="long", locale='en_US')
|
602 |
+
u'12 thousand'
|
603 |
+
>>> format_compact_decimal(12345, format_type="short", locale='en_US', fraction_digits=2)
|
604 |
+
u'12.34K'
|
605 |
+
>>> format_compact_decimal(1234567, format_type="short", locale="ja_JP")
|
606 |
+
u'123万'
|
607 |
+
>>> format_compact_decimal(2345678, format_type="long", locale="mk")
|
608 |
+
u'2 милиони'
|
609 |
+
>>> format_compact_decimal(21000000, format_type="long", locale="mk")
|
610 |
+
u'21 милион'
|
611 |
+
>>> format_compact_decimal(12345, format_type="short", locale='ar_EG', fraction_digits=2, numbering_system='default')
|
612 |
+
u'12٫34\xa0ألف'
|
613 |
+
|
614 |
+
:param number: the number to format
|
615 |
+
:param format_type: Compact format to use ("short" or "long")
|
616 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
617 |
+
:param fraction_digits: Number of digits after the decimal point to use. Defaults to `0`.
|
618 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
619 |
+
The special value "default" will use the default numbering system of the locale.
|
620 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
621 |
+
"""
|
622 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
623 |
+
compact_format = locale.compact_decimal_formats[format_type]
|
624 |
+
number, format = _get_compact_format(number, compact_format, locale, fraction_digits)
|
625 |
+
# Did not find a format, fall back.
|
626 |
+
if format is None:
|
627 |
+
format = locale.decimal_formats[None]
|
628 |
+
pattern = parse_pattern(format)
|
629 |
+
return pattern.apply(number, locale, decimal_quantization=False, numbering_system=numbering_system)
|
630 |
+
|
631 |
+
|
632 |
+
def _get_compact_format(
|
633 |
+
number: float | decimal.Decimal | str,
|
634 |
+
compact_format: LocaleDataDict,
|
635 |
+
locale: Locale,
|
636 |
+
fraction_digits: int,
|
637 |
+
) -> tuple[decimal.Decimal, NumberPattern | None]:
|
638 |
+
"""Returns the number after dividing by the unit and the format pattern to use.
|
639 |
+
The algorithm is described here:
|
640 |
+
https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats.
|
641 |
+
"""
|
642 |
+
if not isinstance(number, decimal.Decimal):
|
643 |
+
number = decimal.Decimal(str(number))
|
644 |
+
if number.is_nan() or number.is_infinite():
|
645 |
+
return number, None
|
646 |
+
format = None
|
647 |
+
for magnitude in sorted([int(m) for m in compact_format["other"]], reverse=True):
|
648 |
+
if abs(number) >= magnitude:
|
649 |
+
# check the pattern using "other" as the amount
|
650 |
+
format = compact_format["other"][str(magnitude)]
|
651 |
+
pattern = parse_pattern(format).pattern
|
652 |
+
# if the pattern is "0", we do not divide the number
|
653 |
+
if pattern == "0":
|
654 |
+
break
|
655 |
+
# otherwise, we need to divide the number by the magnitude but remove zeros
|
656 |
+
# equal to the number of 0's in the pattern minus 1
|
657 |
+
number = cast(decimal.Decimal, number / (magnitude // (10 ** (pattern.count("0") - 1))))
|
658 |
+
# round to the number of fraction digits requested
|
659 |
+
rounded = round(number, fraction_digits)
|
660 |
+
# if the remaining number is singular, use the singular format
|
661 |
+
plural_form = locale.plural_form(abs(number))
|
662 |
+
if plural_form not in compact_format:
|
663 |
+
plural_form = "other"
|
664 |
+
if number == 1 and "1" in compact_format:
|
665 |
+
plural_form = "1"
|
666 |
+
format = compact_format[plural_form][str(magnitude)]
|
667 |
+
number = rounded
|
668 |
+
break
|
669 |
+
return number, format
|
670 |
+
|
671 |
+
|
672 |
+
class UnknownCurrencyFormatError(KeyError):
|
673 |
+
"""Exception raised when an unknown currency format is requested."""
|
674 |
+
|
675 |
+
|
676 |
+
def format_currency(
|
677 |
+
number: float | decimal.Decimal | str,
|
678 |
+
currency: str,
|
679 |
+
format: str | NumberPattern | None = None,
|
680 |
+
locale: Locale | str | None = None,
|
681 |
+
currency_digits: bool = True,
|
682 |
+
format_type: Literal["name", "standard", "accounting"] = "standard",
|
683 |
+
decimal_quantization: bool = True,
|
684 |
+
group_separator: bool = True,
|
685 |
+
*,
|
686 |
+
numbering_system: Literal["default"] | str = "latn",
|
687 |
+
) -> str:
|
688 |
+
"""Return formatted currency value.
|
689 |
+
|
690 |
+
>>> format_currency(1099.98, 'USD', locale='en_US')
|
691 |
+
'$1,099.98'
|
692 |
+
>>> format_currency(1099.98, 'USD', locale='es_CO')
|
693 |
+
u'US$1.099,98'
|
694 |
+
>>> format_currency(1099.98, 'EUR', locale='de_DE')
|
695 |
+
u'1.099,98\\xa0\\u20ac'
|
696 |
+
>>> format_currency(1099.98, 'EGP', locale='ar_EG', numbering_system='default')
|
697 |
+
u'\u200f1٬099٫98\xa0ج.م.\u200f'
|
698 |
+
|
699 |
+
The format can also be specified explicitly. The currency is
|
700 |
+
placed with the '¤' sign. As the sign gets repeated the format
|
701 |
+
expands (¤ being the symbol, ¤¤ is the currency abbreviation and
|
702 |
+
¤¤¤ is the full name of the currency):
|
703 |
+
|
704 |
+
>>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00', locale='en_US')
|
705 |
+
u'EUR 1,099.98'
|
706 |
+
>>> format_currency(1099.98, 'EUR', u'#,##0.00 \xa4\xa4\xa4', locale='en_US')
|
707 |
+
u'1,099.98 euros'
|
708 |
+
|
709 |
+
Currencies usually have a specific number of decimal digits. This function
|
710 |
+
favours that information over the given format:
|
711 |
+
|
712 |
+
>>> format_currency(1099.98, 'JPY', locale='en_US')
|
713 |
+
u'\\xa51,100'
|
714 |
+
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
|
715 |
+
u'1.099,98'
|
716 |
+
|
717 |
+
However, the number of decimal digits can be overridden from the currency
|
718 |
+
information, by setting the last parameter to ``False``:
|
719 |
+
|
720 |
+
>>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
|
721 |
+
u'\\xa51,099.98'
|
722 |
+
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
|
723 |
+
u'1.099,98'
|
724 |
+
|
725 |
+
If a format is not specified the type of currency format to use
|
726 |
+
from the locale can be specified:
|
727 |
+
|
728 |
+
>>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
|
729 |
+
u'\\u20ac1,099.98'
|
730 |
+
|
731 |
+
When the given currency format type is not available, an exception is
|
732 |
+
raised:
|
733 |
+
|
734 |
+
>>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
|
735 |
+
Traceback (most recent call last):
|
736 |
+
...
|
737 |
+
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
|
738 |
+
|
739 |
+
>>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False)
|
740 |
+
u'$101299.98'
|
741 |
+
|
742 |
+
>>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True)
|
743 |
+
u'$101,299.98'
|
744 |
+
|
745 |
+
You can also pass format_type='name' to use long display names. The order of
|
746 |
+
the number and currency name, along with the correct localized plural form
|
747 |
+
of the currency name, is chosen according to locale:
|
748 |
+
|
749 |
+
>>> format_currency(1, 'USD', locale='en_US', format_type='name')
|
750 |
+
u'1.00 US dollar'
|
751 |
+
>>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
|
752 |
+
u'1,099.98 US dollars'
|
753 |
+
>>> format_currency(1099.98, 'USD', locale='ee', format_type='name')
|
754 |
+
u'us ga dollar 1,099.98'
|
755 |
+
|
756 |
+
By default the locale is allowed to truncate and round a high-precision
|
757 |
+
number by forcing its format pattern onto the decimal part. You can bypass
|
758 |
+
this behavior with the `decimal_quantization` parameter:
|
759 |
+
|
760 |
+
>>> format_currency(1099.9876, 'USD', locale='en_US')
|
761 |
+
u'$1,099.99'
|
762 |
+
>>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False)
|
763 |
+
u'$1,099.9876'
|
764 |
+
|
765 |
+
:param number: the number to format
|
766 |
+
:param currency: the currency code
|
767 |
+
:param format: the format string to use
|
768 |
+
:param locale: the `Locale` object or locale identifier.
|
769 |
+
Defaults to the system currency locale or numeric locale.
|
770 |
+
:param currency_digits: use the currency's natural number of decimal digits
|
771 |
+
:param format_type: the currency format type to use
|
772 |
+
:param decimal_quantization: Truncate and round high-precision numbers to
|
773 |
+
the format pattern. Defaults to `True`.
|
774 |
+
:param group_separator: Boolean to switch group separator on/off in a locale's
|
775 |
+
number format.
|
776 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
777 |
+
The special value "default" will use the default numbering system of the locale.
|
778 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
779 |
+
"""
|
780 |
+
locale = Locale.parse(locale or LC_MONETARY)
|
781 |
+
|
782 |
+
if format_type == 'name':
|
783 |
+
return _format_currency_long_name(
|
784 |
+
number,
|
785 |
+
currency,
|
786 |
+
locale=locale,
|
787 |
+
format=format,
|
788 |
+
currency_digits=currency_digits,
|
789 |
+
decimal_quantization=decimal_quantization,
|
790 |
+
group_separator=group_separator,
|
791 |
+
numbering_system=numbering_system,
|
792 |
+
)
|
793 |
+
|
794 |
+
if format:
|
795 |
+
pattern = parse_pattern(format)
|
796 |
+
else:
|
797 |
+
try:
|
798 |
+
pattern = locale.currency_formats[format_type]
|
799 |
+
except KeyError:
|
800 |
+
raise UnknownCurrencyFormatError(f"{format_type!r} is not a known currency format type") from None
|
801 |
+
|
802 |
+
return pattern.apply(
|
803 |
+
number, locale, currency=currency, currency_digits=currency_digits,
|
804 |
+
decimal_quantization=decimal_quantization, group_separator=group_separator, numbering_system=numbering_system)
|
805 |
+
|
806 |
+
|
807 |
+
def _format_currency_long_name(
|
808 |
+
number: float | decimal.Decimal | str,
|
809 |
+
currency: str,
|
810 |
+
*,
|
811 |
+
locale: Locale,
|
812 |
+
format: str | NumberPattern | None,
|
813 |
+
currency_digits: bool,
|
814 |
+
decimal_quantization: bool,
|
815 |
+
group_separator: bool,
|
816 |
+
numbering_system: Literal["default"] | str,
|
817 |
+
) -> str:
|
818 |
+
# Algorithm described here:
|
819 |
+
# https://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
|
820 |
+
|
821 |
+
# Step 1.
|
822 |
+
# There are no examples of items with explicit count (0 or 1) in current
|
823 |
+
# locale data. So there is no point implementing that.
|
824 |
+
# Step 2.
|
825 |
+
|
826 |
+
# Correct number to numeric type, important for looking up plural rules:
|
827 |
+
number_n = float(number) if isinstance(number, str) else number
|
828 |
+
|
829 |
+
# Step 3.
|
830 |
+
unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale)
|
831 |
+
|
832 |
+
# Step 4.
|
833 |
+
display_name = get_currency_name(currency, count=number_n, locale=locale)
|
834 |
+
|
835 |
+
# Step 5.
|
836 |
+
if not format:
|
837 |
+
format = locale.decimal_formats[None]
|
838 |
+
|
839 |
+
pattern = parse_pattern(format)
|
840 |
+
|
841 |
+
number_part = pattern.apply(
|
842 |
+
number, locale, currency=currency, currency_digits=currency_digits,
|
843 |
+
decimal_quantization=decimal_quantization, group_separator=group_separator, numbering_system=numbering_system)
|
844 |
+
|
845 |
+
return unit_pattern.format(number_part, display_name)
|
846 |
+
|
847 |
+
|
848 |
+
def format_compact_currency(
|
849 |
+
number: float | decimal.Decimal | str,
|
850 |
+
currency: str,
|
851 |
+
*,
|
852 |
+
format_type: Literal["short"] = "short",
|
853 |
+
locale: Locale | str | None = None,
|
854 |
+
fraction_digits: int = 0,
|
855 |
+
numbering_system: Literal["default"] | str = "latn",
|
856 |
+
) -> str:
|
857 |
+
"""Format a number as a currency value in compact form.
|
858 |
+
|
859 |
+
>>> format_compact_currency(12345, 'USD', locale='en_US')
|
860 |
+
u'$12K'
|
861 |
+
>>> format_compact_currency(123456789, 'USD', locale='en_US', fraction_digits=2)
|
862 |
+
u'$123.46M'
|
863 |
+
>>> format_compact_currency(123456789, 'EUR', locale='de_DE', fraction_digits=1)
|
864 |
+
'123,5\xa0Mio.\xa0€'
|
865 |
+
|
866 |
+
:param number: the number to format
|
867 |
+
:param currency: the currency code
|
868 |
+
:param format_type: the compact format type to use. Defaults to "short".
|
869 |
+
:param locale: the `Locale` object or locale identifier.
|
870 |
+
Defaults to the system currency locale or numeric locale.
|
871 |
+
:param fraction_digits: Number of digits after the decimal point to use. Defaults to `0`.
|
872 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
873 |
+
The special value "default" will use the default numbering system of the locale.
|
874 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
875 |
+
"""
|
876 |
+
locale = Locale.parse(locale or LC_MONETARY)
|
877 |
+
try:
|
878 |
+
compact_format = locale.compact_currency_formats[format_type]
|
879 |
+
except KeyError as error:
|
880 |
+
raise UnknownCurrencyFormatError(f"{format_type!r} is not a known compact currency format type") from error
|
881 |
+
number, format = _get_compact_format(number, compact_format, locale, fraction_digits)
|
882 |
+
# Did not find a format, fall back.
|
883 |
+
if format is None or "¤" not in str(format):
|
884 |
+
# find first format that has a currency symbol
|
885 |
+
for magnitude in compact_format['other']:
|
886 |
+
format = compact_format['other'][magnitude].pattern
|
887 |
+
if '¤' not in format:
|
888 |
+
continue
|
889 |
+
# remove characters that are not the currency symbol, 0's or spaces
|
890 |
+
format = re.sub(r'[^0\s\¤]', '', format)
|
891 |
+
# compress adjacent spaces into one
|
892 |
+
format = re.sub(r'(\s)\s+', r'\1', format).strip()
|
893 |
+
break
|
894 |
+
if format is None:
|
895 |
+
raise ValueError('No compact currency format found for the given number and locale.')
|
896 |
+
pattern = parse_pattern(format)
|
897 |
+
return pattern.apply(number, locale, currency=currency, currency_digits=False, decimal_quantization=False,
|
898 |
+
numbering_system=numbering_system)
|
899 |
+
|
900 |
+
|
901 |
+
def format_percent(
|
902 |
+
number: float | decimal.Decimal | str,
|
903 |
+
format: str | NumberPattern | None = None,
|
904 |
+
locale: Locale | str | None = None,
|
905 |
+
decimal_quantization: bool = True,
|
906 |
+
group_separator: bool = True,
|
907 |
+
*,
|
908 |
+
numbering_system: Literal["default"] | str = "latn",
|
909 |
+
) -> str:
|
910 |
+
"""Return formatted percent value for a specific locale.
|
911 |
+
|
912 |
+
>>> format_percent(0.34, locale='en_US')
|
913 |
+
u'34%'
|
914 |
+
>>> format_percent(25.1234, locale='en_US')
|
915 |
+
u'2,512%'
|
916 |
+
>>> format_percent(25.1234, locale='sv_SE')
|
917 |
+
u'2\\xa0512\\xa0%'
|
918 |
+
>>> format_percent(25.1234, locale='ar_EG', numbering_system='default')
|
919 |
+
u'2٬512%'
|
920 |
+
|
921 |
+
The format pattern can also be specified explicitly:
|
922 |
+
|
923 |
+
>>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
|
924 |
+
u'25,123\u2030'
|
925 |
+
|
926 |
+
By default the locale is allowed to truncate and round a high-precision
|
927 |
+
number by forcing its format pattern onto the decimal part. You can bypass
|
928 |
+
this behavior with the `decimal_quantization` parameter:
|
929 |
+
|
930 |
+
>>> format_percent(23.9876, locale='en_US')
|
931 |
+
u'2,399%'
|
932 |
+
>>> format_percent(23.9876, locale='en_US', decimal_quantization=False)
|
933 |
+
u'2,398.76%'
|
934 |
+
|
935 |
+
>>> format_percent(229291.1234, locale='pt_BR', group_separator=False)
|
936 |
+
u'22929112%'
|
937 |
+
|
938 |
+
>>> format_percent(229291.1234, locale='pt_BR', group_separator=True)
|
939 |
+
u'22.929.112%'
|
940 |
+
|
941 |
+
:param number: the percent number to format
|
942 |
+
:param format:
|
943 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
944 |
+
:param decimal_quantization: Truncate and round high-precision numbers to
|
945 |
+
the format pattern. Defaults to `True`.
|
946 |
+
:param group_separator: Boolean to switch group separator on/off in a locale's
|
947 |
+
number format.
|
948 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
949 |
+
The special value "default" will use the default numbering system of the locale.
|
950 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
951 |
+
"""
|
952 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
953 |
+
if not format:
|
954 |
+
format = locale.percent_formats[None]
|
955 |
+
pattern = parse_pattern(format)
|
956 |
+
return pattern.apply(
|
957 |
+
number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator,
|
958 |
+
numbering_system=numbering_system,
|
959 |
+
)
|
960 |
+
|
961 |
+
|
962 |
+
def format_scientific(
|
963 |
+
number: float | decimal.Decimal | str,
|
964 |
+
format: str | NumberPattern | None = None,
|
965 |
+
locale: Locale | str | None = None,
|
966 |
+
decimal_quantization: bool = True,
|
967 |
+
*,
|
968 |
+
numbering_system: Literal["default"] | str = "latn",
|
969 |
+
) -> str:
|
970 |
+
"""Return value formatted in scientific notation for a specific locale.
|
971 |
+
|
972 |
+
>>> format_scientific(10000, locale='en_US')
|
973 |
+
u'1E4'
|
974 |
+
>>> format_scientific(10000, locale='ar_EG', numbering_system='default')
|
975 |
+
u'1أس4'
|
976 |
+
|
977 |
+
The format pattern can also be specified explicitly:
|
978 |
+
|
979 |
+
>>> format_scientific(1234567, u'##0.##E00', locale='en_US')
|
980 |
+
u'1.23E06'
|
981 |
+
|
982 |
+
By default the locale is allowed to truncate and round a high-precision
|
983 |
+
number by forcing its format pattern onto the decimal part. You can bypass
|
984 |
+
this behavior with the `decimal_quantization` parameter:
|
985 |
+
|
986 |
+
>>> format_scientific(1234.9876, u'#.##E0', locale='en_US')
|
987 |
+
u'1.23E3'
|
988 |
+
>>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False)
|
989 |
+
u'1.2349876E3'
|
990 |
+
|
991 |
+
:param number: the number to format
|
992 |
+
:param format:
|
993 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
994 |
+
:param decimal_quantization: Truncate and round high-precision numbers to
|
995 |
+
the format pattern. Defaults to `True`.
|
996 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
997 |
+
The special value "default" will use the default numbering system of the locale.
|
998 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
999 |
+
"""
|
1000 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
1001 |
+
if not format:
|
1002 |
+
format = locale.scientific_formats[None]
|
1003 |
+
pattern = parse_pattern(format)
|
1004 |
+
return pattern.apply(
|
1005 |
+
number, locale, decimal_quantization=decimal_quantization, numbering_system=numbering_system)
|
1006 |
+
|
1007 |
+
|
1008 |
+
class NumberFormatError(ValueError):
|
1009 |
+
"""Exception raised when a string cannot be parsed into a number."""
|
1010 |
+
|
1011 |
+
def __init__(self, message: str, suggestions: list[str] | None = None) -> None:
|
1012 |
+
super().__init__(message)
|
1013 |
+
#: a list of properly formatted numbers derived from the invalid input
|
1014 |
+
self.suggestions = suggestions
|
1015 |
+
|
1016 |
+
|
1017 |
+
SPACE_CHARS = {
|
1018 |
+
' ', # space
|
1019 |
+
'\xa0', # no-break space
|
1020 |
+
'\u202f', # narrow no-break space
|
1021 |
+
}
|
1022 |
+
|
1023 |
+
SPACE_CHARS_RE = re.compile('|'.join(SPACE_CHARS))
|
1024 |
+
|
1025 |
+
|
1026 |
+
def parse_number(
|
1027 |
+
string: str,
|
1028 |
+
locale: Locale | str | None = None,
|
1029 |
+
*,
|
1030 |
+
numbering_system: Literal["default"] | str = "latn",
|
1031 |
+
) -> int:
|
1032 |
+
"""Parse localized number string into an integer.
|
1033 |
+
|
1034 |
+
>>> parse_number('1,099', locale='en_US')
|
1035 |
+
1099
|
1036 |
+
>>> parse_number('1.099', locale='de_DE')
|
1037 |
+
1099
|
1038 |
+
|
1039 |
+
When the given string cannot be parsed, an exception is raised:
|
1040 |
+
|
1041 |
+
>>> parse_number('1.099,98', locale='de')
|
1042 |
+
Traceback (most recent call last):
|
1043 |
+
...
|
1044 |
+
NumberFormatError: '1.099,98' is not a valid number
|
1045 |
+
|
1046 |
+
:param string: the string to parse
|
1047 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
1048 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
1049 |
+
The special value "default" will use the default numbering system of the locale.
|
1050 |
+
:return: the parsed number
|
1051 |
+
:raise `NumberFormatError`: if the string can not be converted to a number
|
1052 |
+
:raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
|
1053 |
+
"""
|
1054 |
+
group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
|
1055 |
+
|
1056 |
+
if (
|
1057 |
+
group_symbol in SPACE_CHARS and # if the grouping symbol is a kind of space,
|
1058 |
+
group_symbol not in string and # and the string to be parsed does not contain it,
|
1059 |
+
SPACE_CHARS_RE.search(string) # but it does contain any other kind of space instead,
|
1060 |
+
):
|
1061 |
+
# ... it's reasonable to assume it is taking the place of the grouping symbol.
|
1062 |
+
string = SPACE_CHARS_RE.sub(group_symbol, string)
|
1063 |
+
|
1064 |
+
try:
|
1065 |
+
return int(string.replace(group_symbol, ''))
|
1066 |
+
except ValueError as ve:
|
1067 |
+
raise NumberFormatError(f"{string!r} is not a valid number") from ve
|
1068 |
+
|
1069 |
+
|
1070 |
+
def parse_decimal(
|
1071 |
+
string: str,
|
1072 |
+
locale: Locale | str | None = None,
|
1073 |
+
strict: bool = False,
|
1074 |
+
*,
|
1075 |
+
numbering_system: Literal["default"] | str = "latn",
|
1076 |
+
) -> decimal.Decimal:
|
1077 |
+
"""Parse localized decimal string into a decimal.
|
1078 |
+
|
1079 |
+
>>> parse_decimal('1,099.98', locale='en_US')
|
1080 |
+
Decimal('1099.98')
|
1081 |
+
>>> parse_decimal('1.099,98', locale='de')
|
1082 |
+
Decimal('1099.98')
|
1083 |
+
>>> parse_decimal('12 345,123', locale='ru')
|
1084 |
+
Decimal('12345.123')
|
1085 |
+
>>> parse_decimal('1٬099٫98', locale='ar_EG', numbering_system='default')
|
1086 |
+
Decimal('1099.98')
|
1087 |
+
|
1088 |
+
When the given string cannot be parsed, an exception is raised:
|
1089 |
+
|
1090 |
+
>>> parse_decimal('2,109,998', locale='de')
|
1091 |
+
Traceback (most recent call last):
|
1092 |
+
...
|
1093 |
+
NumberFormatError: '2,109,998' is not a valid decimal number
|
1094 |
+
|
1095 |
+
If `strict` is set to `True` and the given string contains a number
|
1096 |
+
formatted in an irregular way, an exception is raised:
|
1097 |
+
|
1098 |
+
>>> parse_decimal('30.00', locale='de', strict=True)
|
1099 |
+
Traceback (most recent call last):
|
1100 |
+
...
|
1101 |
+
NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'?
|
1102 |
+
|
1103 |
+
>>> parse_decimal('0.00', locale='de', strict=True)
|
1104 |
+
Traceback (most recent call last):
|
1105 |
+
...
|
1106 |
+
NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'?
|
1107 |
+
|
1108 |
+
:param string: the string to parse
|
1109 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
1110 |
+
:param strict: controls whether numbers formatted in a weird way are
|
1111 |
+
accepted or rejected
|
1112 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
1113 |
+
The special value "default" will use the default numbering system of the locale.
|
1114 |
+
:raise NumberFormatError: if the string can not be converted to a
|
1115 |
+
decimal number
|
1116 |
+
:raise UnsupportedNumberingSystemError: if the numbering system is not supported by the locale.
|
1117 |
+
"""
|
1118 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
1119 |
+
group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
|
1120 |
+
decimal_symbol = get_decimal_symbol(locale, numbering_system=numbering_system)
|
1121 |
+
|
1122 |
+
if not strict and (
|
1123 |
+
group_symbol in SPACE_CHARS and # if the grouping symbol is a kind of space,
|
1124 |
+
group_symbol not in string and # and the string to be parsed does not contain it,
|
1125 |
+
SPACE_CHARS_RE.search(string) # but it does contain any other kind of space instead,
|
1126 |
+
):
|
1127 |
+
# ... it's reasonable to assume it is taking the place of the grouping symbol.
|
1128 |
+
string = SPACE_CHARS_RE.sub(group_symbol, string)
|
1129 |
+
|
1130 |
+
try:
|
1131 |
+
parsed = decimal.Decimal(string.replace(group_symbol, '')
|
1132 |
+
.replace(decimal_symbol, '.'))
|
1133 |
+
except decimal.InvalidOperation as exc:
|
1134 |
+
raise NumberFormatError(f"{string!r} is not a valid decimal number") from exc
|
1135 |
+
if strict and group_symbol in string:
|
1136 |
+
proper = format_decimal(parsed, locale=locale, decimal_quantization=False, numbering_system=numbering_system)
|
1137 |
+
if string != proper and proper != _remove_trailing_zeros_after_decimal(string, decimal_symbol):
|
1138 |
+
try:
|
1139 |
+
parsed_alt = decimal.Decimal(string.replace(decimal_symbol, '')
|
1140 |
+
.replace(group_symbol, '.'))
|
1141 |
+
except decimal.InvalidOperation as exc:
|
1142 |
+
raise NumberFormatError(
|
1143 |
+
f"{string!r} is not a properly formatted decimal number. "
|
1144 |
+
f"Did you mean {proper!r}?",
|
1145 |
+
suggestions=[proper],
|
1146 |
+
) from exc
|
1147 |
+
else:
|
1148 |
+
proper_alt = format_decimal(
|
1149 |
+
parsed_alt,
|
1150 |
+
locale=locale,
|
1151 |
+
decimal_quantization=False,
|
1152 |
+
numbering_system=numbering_system,
|
1153 |
+
)
|
1154 |
+
if proper_alt == proper:
|
1155 |
+
raise NumberFormatError(
|
1156 |
+
f"{string!r} is not a properly formatted decimal number. "
|
1157 |
+
f"Did you mean {proper!r}?",
|
1158 |
+
suggestions=[proper],
|
1159 |
+
)
|
1160 |
+
else:
|
1161 |
+
raise NumberFormatError(
|
1162 |
+
f"{string!r} is not a properly formatted decimal number. "
|
1163 |
+
f"Did you mean {proper!r}? Or maybe {proper_alt!r}?",
|
1164 |
+
suggestions=[proper, proper_alt],
|
1165 |
+
)
|
1166 |
+
return parsed
|
1167 |
+
|
1168 |
+
|
1169 |
+
def _remove_trailing_zeros_after_decimal(string: str, decimal_symbol: str) -> str:
|
1170 |
+
"""
|
1171 |
+
Remove trailing zeros from the decimal part of a numeric string.
|
1172 |
+
|
1173 |
+
This function takes a string representing a numeric value and a decimal symbol.
|
1174 |
+
It removes any trailing zeros that appear after the decimal symbol in the number.
|
1175 |
+
If the decimal part becomes empty after removing trailing zeros, the decimal symbol
|
1176 |
+
is also removed. If the string does not contain the decimal symbol, it is returned unchanged.
|
1177 |
+
|
1178 |
+
:param string: The numeric string from which to remove trailing zeros.
|
1179 |
+
:type string: str
|
1180 |
+
:param decimal_symbol: The symbol used to denote the decimal point.
|
1181 |
+
:type decimal_symbol: str
|
1182 |
+
:return: The numeric string with trailing zeros removed from its decimal part.
|
1183 |
+
:rtype: str
|
1184 |
+
|
1185 |
+
Example:
|
1186 |
+
>>> _remove_trailing_zeros_after_decimal("123.4500", ".")
|
1187 |
+
'123.45'
|
1188 |
+
>>> _remove_trailing_zeros_after_decimal("100.000", ".")
|
1189 |
+
'100'
|
1190 |
+
>>> _remove_trailing_zeros_after_decimal("100", ".")
|
1191 |
+
'100'
|
1192 |
+
"""
|
1193 |
+
integer_part, _, decimal_part = string.partition(decimal_symbol)
|
1194 |
+
|
1195 |
+
if decimal_part:
|
1196 |
+
decimal_part = decimal_part.rstrip("0")
|
1197 |
+
if decimal_part:
|
1198 |
+
return integer_part + decimal_symbol + decimal_part
|
1199 |
+
return integer_part
|
1200 |
+
|
1201 |
+
return string
|
1202 |
+
|
1203 |
+
|
1204 |
+
PREFIX_END = r'[^0-9@#.,]'
|
1205 |
+
NUMBER_TOKEN = r'[0-9@#.,E+]'
|
1206 |
+
|
1207 |
+
PREFIX_PATTERN = r"(?P<prefix>(?:'[^']*'|%s)*)" % PREFIX_END
|
1208 |
+
NUMBER_PATTERN = r"(?P<number>%s*)" % NUMBER_TOKEN
|
1209 |
+
SUFFIX_PATTERN = r"(?P<suffix>.*)"
|
1210 |
+
|
1211 |
+
number_re = re.compile(f"{PREFIX_PATTERN}{NUMBER_PATTERN}{SUFFIX_PATTERN}")
|
1212 |
+
|
1213 |
+
|
1214 |
+
def parse_grouping(p: str) -> tuple[int, int]:
|
1215 |
+
"""Parse primary and secondary digit grouping
|
1216 |
+
|
1217 |
+
>>> parse_grouping('##')
|
1218 |
+
(1000, 1000)
|
1219 |
+
>>> parse_grouping('#,###')
|
1220 |
+
(3, 3)
|
1221 |
+
>>> parse_grouping('#,####,###')
|
1222 |
+
(3, 4)
|
1223 |
+
"""
|
1224 |
+
width = len(p)
|
1225 |
+
g1 = p.rfind(',')
|
1226 |
+
if g1 == -1:
|
1227 |
+
return 1000, 1000
|
1228 |
+
g1 = width - g1 - 1
|
1229 |
+
g2 = p[:-g1 - 1].rfind(',')
|
1230 |
+
if g2 == -1:
|
1231 |
+
return g1, g1
|
1232 |
+
g2 = width - g1 - g2 - 2
|
1233 |
+
return g1, g2
|
1234 |
+
|
1235 |
+
|
1236 |
+
def parse_pattern(pattern: NumberPattern | str) -> NumberPattern:
|
1237 |
+
"""Parse number format patterns"""
|
1238 |
+
if isinstance(pattern, NumberPattern):
|
1239 |
+
return pattern
|
1240 |
+
|
1241 |
+
def _match_number(pattern):
|
1242 |
+
rv = number_re.search(pattern)
|
1243 |
+
if rv is None:
|
1244 |
+
raise ValueError(f"Invalid number pattern {pattern!r}")
|
1245 |
+
return rv.groups()
|
1246 |
+
|
1247 |
+
pos_pattern = pattern
|
1248 |
+
|
1249 |
+
# Do we have a negative subpattern?
|
1250 |
+
if ';' in pattern:
|
1251 |
+
pos_pattern, neg_pattern = pattern.split(';', 1)
|
1252 |
+
pos_prefix, number, pos_suffix = _match_number(pos_pattern)
|
1253 |
+
neg_prefix, _, neg_suffix = _match_number(neg_pattern)
|
1254 |
+
else:
|
1255 |
+
pos_prefix, number, pos_suffix = _match_number(pos_pattern)
|
1256 |
+
neg_prefix = f"-{pos_prefix}"
|
1257 |
+
neg_suffix = pos_suffix
|
1258 |
+
if 'E' in number:
|
1259 |
+
number, exp = number.split('E', 1)
|
1260 |
+
else:
|
1261 |
+
exp = None
|
1262 |
+
if '@' in number and '.' in number and '0' in number:
|
1263 |
+
raise ValueError('Significant digit patterns can not contain "@" or "0"')
|
1264 |
+
if '.' in number:
|
1265 |
+
integer, fraction = number.rsplit('.', 1)
|
1266 |
+
else:
|
1267 |
+
integer = number
|
1268 |
+
fraction = ''
|
1269 |
+
|
1270 |
+
def parse_precision(p):
|
1271 |
+
"""Calculate the min and max allowed digits"""
|
1272 |
+
min = max = 0
|
1273 |
+
for c in p:
|
1274 |
+
if c in '@0':
|
1275 |
+
min += 1
|
1276 |
+
max += 1
|
1277 |
+
elif c == '#':
|
1278 |
+
max += 1
|
1279 |
+
elif c == ',':
|
1280 |
+
continue
|
1281 |
+
else:
|
1282 |
+
break
|
1283 |
+
return min, max
|
1284 |
+
|
1285 |
+
int_prec = parse_precision(integer)
|
1286 |
+
frac_prec = parse_precision(fraction)
|
1287 |
+
if exp:
|
1288 |
+
exp_plus = exp.startswith('+')
|
1289 |
+
exp = exp.lstrip('+')
|
1290 |
+
exp_prec = parse_precision(exp)
|
1291 |
+
else:
|
1292 |
+
exp_plus = None
|
1293 |
+
exp_prec = None
|
1294 |
+
grouping = parse_grouping(integer)
|
1295 |
+
return NumberPattern(pattern, (pos_prefix, neg_prefix),
|
1296 |
+
(pos_suffix, neg_suffix), grouping,
|
1297 |
+
int_prec, frac_prec,
|
1298 |
+
exp_prec, exp_plus, number)
|
1299 |
+
|
1300 |
+
|
1301 |
+
class NumberPattern:
|
1302 |
+
|
1303 |
+
def __init__(
|
1304 |
+
self,
|
1305 |
+
pattern: str,
|
1306 |
+
prefix: tuple[str, str],
|
1307 |
+
suffix: tuple[str, str],
|
1308 |
+
grouping: tuple[int, int],
|
1309 |
+
int_prec: tuple[int, int],
|
1310 |
+
frac_prec: tuple[int, int],
|
1311 |
+
exp_prec: tuple[int, int] | None,
|
1312 |
+
exp_plus: bool | None,
|
1313 |
+
number_pattern: str | None = None,
|
1314 |
+
) -> None:
|
1315 |
+
# Metadata of the decomposed parsed pattern.
|
1316 |
+
self.pattern = pattern
|
1317 |
+
self.prefix = prefix
|
1318 |
+
self.suffix = suffix
|
1319 |
+
self.number_pattern = number_pattern
|
1320 |
+
self.grouping = grouping
|
1321 |
+
self.int_prec = int_prec
|
1322 |
+
self.frac_prec = frac_prec
|
1323 |
+
self.exp_prec = exp_prec
|
1324 |
+
self.exp_plus = exp_plus
|
1325 |
+
self.scale = self.compute_scale()
|
1326 |
+
|
1327 |
+
def __repr__(self) -> str:
|
1328 |
+
return f"<{type(self).__name__} {self.pattern!r}>"
|
1329 |
+
|
1330 |
+
def compute_scale(self) -> Literal[0, 2, 3]:
|
1331 |
+
"""Return the scaling factor to apply to the number before rendering.
|
1332 |
+
|
1333 |
+
Auto-set to a factor of 2 or 3 if presence of a ``%`` or ``‰`` sign is
|
1334 |
+
detected in the prefix or suffix of the pattern. Default is to not mess
|
1335 |
+
with the scale at all and keep it to 0.
|
1336 |
+
"""
|
1337 |
+
scale = 0
|
1338 |
+
if '%' in ''.join(self.prefix + self.suffix):
|
1339 |
+
scale = 2
|
1340 |
+
elif '‰' in ''.join(self.prefix + self.suffix):
|
1341 |
+
scale = 3
|
1342 |
+
return scale
|
1343 |
+
|
1344 |
+
def scientific_notation_elements(
|
1345 |
+
self,
|
1346 |
+
value: decimal.Decimal,
|
1347 |
+
locale: Locale | str | None,
|
1348 |
+
*,
|
1349 |
+
numbering_system: Literal["default"] | str = "latn",
|
1350 |
+
) -> tuple[decimal.Decimal, int, str]:
|
1351 |
+
""" Returns normalized scientific notation components of a value.
|
1352 |
+
"""
|
1353 |
+
# Normalize value to only have one lead digit.
|
1354 |
+
exp = value.adjusted()
|
1355 |
+
value = value * get_decimal_quantum(exp)
|
1356 |
+
assert value.adjusted() == 0
|
1357 |
+
|
1358 |
+
# Shift exponent and value by the minimum number of leading digits
|
1359 |
+
# imposed by the rendering pattern. And always make that number
|
1360 |
+
# greater or equal to 1.
|
1361 |
+
lead_shift = max([1, min(self.int_prec)]) - 1
|
1362 |
+
exp = exp - lead_shift
|
1363 |
+
value = value * get_decimal_quantum(-lead_shift)
|
1364 |
+
|
1365 |
+
# Get exponent sign symbol.
|
1366 |
+
exp_sign = ''
|
1367 |
+
if exp < 0:
|
1368 |
+
exp_sign = get_minus_sign_symbol(locale, numbering_system=numbering_system)
|
1369 |
+
elif self.exp_plus:
|
1370 |
+
exp_sign = get_plus_sign_symbol(locale, numbering_system=numbering_system)
|
1371 |
+
|
1372 |
+
# Normalize exponent value now that we have the sign.
|
1373 |
+
exp = abs(exp)
|
1374 |
+
|
1375 |
+
return value, exp, exp_sign
|
1376 |
+
|
1377 |
+
def apply(
|
1378 |
+
self,
|
1379 |
+
value: float | decimal.Decimal | str,
|
1380 |
+
locale: Locale | str | None,
|
1381 |
+
currency: str | None = None,
|
1382 |
+
currency_digits: bool = True,
|
1383 |
+
decimal_quantization: bool = True,
|
1384 |
+
force_frac: tuple[int, int] | None = None,
|
1385 |
+
group_separator: bool = True,
|
1386 |
+
*,
|
1387 |
+
numbering_system: Literal["default"] | str = "latn",
|
1388 |
+
):
|
1389 |
+
"""Renders into a string a number following the defined pattern.
|
1390 |
+
|
1391 |
+
Forced decimal quantization is active by default so we'll produce a
|
1392 |
+
number string that is strictly following CLDR pattern definitions.
|
1393 |
+
|
1394 |
+
:param value: The value to format. If this is not a Decimal object,
|
1395 |
+
it will be cast to one.
|
1396 |
+
:type value: decimal.Decimal|float|int
|
1397 |
+
:param locale: The locale to use for formatting.
|
1398 |
+
:type locale: str|babel.core.Locale
|
1399 |
+
:param currency: Which currency, if any, to format as.
|
1400 |
+
:type currency: str|None
|
1401 |
+
:param currency_digits: Whether or not to use the currency's precision.
|
1402 |
+
If false, the pattern's precision is used.
|
1403 |
+
:type currency_digits: bool
|
1404 |
+
:param decimal_quantization: Whether decimal numbers should be forcibly
|
1405 |
+
quantized to produce a formatted output
|
1406 |
+
strictly matching the CLDR definition for
|
1407 |
+
the locale.
|
1408 |
+
:type decimal_quantization: bool
|
1409 |
+
:param force_frac: DEPRECATED - a forced override for `self.frac_prec`
|
1410 |
+
for a single formatting invocation.
|
1411 |
+
:param group_separator: Whether to use the locale's number group separator.
|
1412 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
1413 |
+
The special value "default" will use the default numbering system of the locale.
|
1414 |
+
:return: Formatted decimal string.
|
1415 |
+
:rtype: str
|
1416 |
+
:raise UnsupportedNumberingSystemError: If the numbering system is not supported by the locale.
|
1417 |
+
"""
|
1418 |
+
if not isinstance(value, decimal.Decimal):
|
1419 |
+
value = decimal.Decimal(str(value))
|
1420 |
+
|
1421 |
+
value = value.scaleb(self.scale)
|
1422 |
+
|
1423 |
+
# Separate the absolute value from its sign.
|
1424 |
+
is_negative = int(value.is_signed())
|
1425 |
+
value = abs(value).normalize()
|
1426 |
+
|
1427 |
+
# Prepare scientific notation metadata.
|
1428 |
+
if self.exp_prec:
|
1429 |
+
value, exp, exp_sign = self.scientific_notation_elements(value, locale, numbering_system=numbering_system)
|
1430 |
+
|
1431 |
+
# Adjust the precision of the fractional part and force it to the
|
1432 |
+
# currency's if necessary.
|
1433 |
+
if force_frac:
|
1434 |
+
# TODO (3.x?): Remove this parameter
|
1435 |
+
warnings.warn(
|
1436 |
+
'The force_frac parameter to NumberPattern.apply() is deprecated.',
|
1437 |
+
DeprecationWarning,
|
1438 |
+
stacklevel=2,
|
1439 |
+
)
|
1440 |
+
frac_prec = force_frac
|
1441 |
+
elif currency and currency_digits:
|
1442 |
+
frac_prec = (get_currency_precision(currency), ) * 2
|
1443 |
+
else:
|
1444 |
+
frac_prec = self.frac_prec
|
1445 |
+
|
1446 |
+
# Bump decimal precision to the natural precision of the number if it
|
1447 |
+
# exceeds the one we're about to use. This adaptative precision is only
|
1448 |
+
# triggered if the decimal quantization is disabled or if a scientific
|
1449 |
+
# notation pattern has a missing mandatory fractional part (as in the
|
1450 |
+
# default '#E0' pattern). This special case has been extensively
|
1451 |
+
# discussed at https://github.com/python-babel/babel/pull/494#issuecomment-307649969 .
|
1452 |
+
if not decimal_quantization or (self.exp_prec and frac_prec == (0, 0)):
|
1453 |
+
frac_prec = (frac_prec[0], max([frac_prec[1], get_decimal_precision(value)]))
|
1454 |
+
|
1455 |
+
# Render scientific notation.
|
1456 |
+
if self.exp_prec:
|
1457 |
+
number = ''.join([
|
1458 |
+
self._quantize_value(value, locale, frac_prec, group_separator, numbering_system=numbering_system),
|
1459 |
+
get_exponential_symbol(locale, numbering_system=numbering_system),
|
1460 |
+
exp_sign, # type: ignore # exp_sign is always defined here
|
1461 |
+
self._format_int(str(exp), self.exp_prec[0], self.exp_prec[1], locale, numbering_system=numbering_system), # type: ignore # exp is always defined here
|
1462 |
+
])
|
1463 |
+
|
1464 |
+
# Is it a significant digits pattern?
|
1465 |
+
elif '@' in self.pattern:
|
1466 |
+
text = self._format_significant(value,
|
1467 |
+
self.int_prec[0],
|
1468 |
+
self.int_prec[1])
|
1469 |
+
a, sep, b = text.partition(".")
|
1470 |
+
number = self._format_int(a, 0, 1000, locale, numbering_system=numbering_system)
|
1471 |
+
if sep:
|
1472 |
+
number += get_decimal_symbol(locale, numbering_system=numbering_system) + b
|
1473 |
+
|
1474 |
+
# A normal number pattern.
|
1475 |
+
else:
|
1476 |
+
number = self._quantize_value(value, locale, frac_prec, group_separator, numbering_system=numbering_system)
|
1477 |
+
|
1478 |
+
retval = ''.join([
|
1479 |
+
self.prefix[is_negative],
|
1480 |
+
number if self.number_pattern != '' else '',
|
1481 |
+
self.suffix[is_negative]])
|
1482 |
+
|
1483 |
+
if '¤' in retval and currency is not None:
|
1484 |
+
retval = retval.replace('¤¤¤', get_currency_name(currency, value, locale))
|
1485 |
+
retval = retval.replace('¤¤', currency.upper())
|
1486 |
+
retval = retval.replace('¤', get_currency_symbol(currency, locale))
|
1487 |
+
|
1488 |
+
# remove single quotes around text, except for doubled single quotes
|
1489 |
+
# which are replaced with a single quote
|
1490 |
+
retval = re.sub(r"'([^']*)'", lambda m: m.group(1) or "'", retval)
|
1491 |
+
|
1492 |
+
return retval
|
1493 |
+
|
1494 |
+
#
|
1495 |
+
# This is one tricky piece of code. The idea is to rely as much as possible
|
1496 |
+
# on the decimal module to minimize the amount of code.
|
1497 |
+
#
|
1498 |
+
# Conceptually, the implementation of this method can be summarized in the
|
1499 |
+
# following steps:
|
1500 |
+
#
|
1501 |
+
# - Move or shift the decimal point (i.e. the exponent) so the maximum
|
1502 |
+
# amount of significant digits fall into the integer part (i.e. to the
|
1503 |
+
# left of the decimal point)
|
1504 |
+
#
|
1505 |
+
# - Round the number to the nearest integer, discarding all the fractional
|
1506 |
+
# part which contained extra digits to be eliminated
|
1507 |
+
#
|
1508 |
+
# - Convert the rounded integer to a string, that will contain the final
|
1509 |
+
# sequence of significant digits already trimmed to the maximum
|
1510 |
+
#
|
1511 |
+
# - Restore the original position of the decimal point, potentially
|
1512 |
+
# padding with zeroes on either side
|
1513 |
+
#
|
1514 |
+
def _format_significant(self, value: decimal.Decimal, minimum: int, maximum: int) -> str:
|
1515 |
+
exp = value.adjusted()
|
1516 |
+
scale = maximum - 1 - exp
|
1517 |
+
digits = str(value.scaleb(scale).quantize(decimal.Decimal(1)))
|
1518 |
+
if scale <= 0:
|
1519 |
+
result = digits + '0' * -scale
|
1520 |
+
else:
|
1521 |
+
intpart = digits[:-scale]
|
1522 |
+
i = len(intpart)
|
1523 |
+
j = i + max(minimum - i, 0)
|
1524 |
+
result = "{intpart}.{pad:0<{fill}}{fracpart}{fracextra}".format(
|
1525 |
+
intpart=intpart or '0',
|
1526 |
+
pad='',
|
1527 |
+
fill=-min(exp + 1, 0),
|
1528 |
+
fracpart=digits[i:j],
|
1529 |
+
fracextra=digits[j:].rstrip('0'),
|
1530 |
+
).rstrip('.')
|
1531 |
+
return result
|
1532 |
+
|
1533 |
+
def _format_int(
|
1534 |
+
self,
|
1535 |
+
value: str,
|
1536 |
+
min: int,
|
1537 |
+
max: int,
|
1538 |
+
locale: Locale | str | None,
|
1539 |
+
*,
|
1540 |
+
numbering_system: Literal["default"] | str,
|
1541 |
+
) -> str:
|
1542 |
+
width = len(value)
|
1543 |
+
if width < min:
|
1544 |
+
value = '0' * (min - width) + value
|
1545 |
+
gsize = self.grouping[0]
|
1546 |
+
ret = ''
|
1547 |
+
symbol = get_group_symbol(locale, numbering_system=numbering_system)
|
1548 |
+
while len(value) > gsize:
|
1549 |
+
ret = symbol + value[-gsize:] + ret
|
1550 |
+
value = value[:-gsize]
|
1551 |
+
gsize = self.grouping[1]
|
1552 |
+
return value + ret
|
1553 |
+
|
1554 |
+
def _quantize_value(
|
1555 |
+
self,
|
1556 |
+
value: decimal.Decimal,
|
1557 |
+
locale: Locale | str | None,
|
1558 |
+
frac_prec: tuple[int, int],
|
1559 |
+
group_separator: bool,
|
1560 |
+
*,
|
1561 |
+
numbering_system: Literal["default"] | str,
|
1562 |
+
) -> str:
|
1563 |
+
# If the number is +/-Infinity, we can't quantize it
|
1564 |
+
if value.is_infinite():
|
1565 |
+
return get_infinity_symbol(locale, numbering_system=numbering_system)
|
1566 |
+
quantum = get_decimal_quantum(frac_prec[1])
|
1567 |
+
rounded = value.quantize(quantum)
|
1568 |
+
a, sep, b = f"{rounded:f}".partition(".")
|
1569 |
+
integer_part = a
|
1570 |
+
if group_separator:
|
1571 |
+
integer_part = self._format_int(a, self.int_prec[0], self.int_prec[1], locale, numbering_system=numbering_system)
|
1572 |
+
number = integer_part + self._format_frac(b or '0', locale=locale, force_frac=frac_prec, numbering_system=numbering_system)
|
1573 |
+
return number
|
1574 |
+
|
1575 |
+
def _format_frac(
|
1576 |
+
self,
|
1577 |
+
value: str,
|
1578 |
+
locale: Locale | str | None,
|
1579 |
+
force_frac: tuple[int, int] | None = None,
|
1580 |
+
*,
|
1581 |
+
numbering_system: Literal["default"] | str,
|
1582 |
+
) -> str:
|
1583 |
+
min, max = force_frac or self.frac_prec
|
1584 |
+
if len(value) < min:
|
1585 |
+
value += ('0' * (min - len(value)))
|
1586 |
+
if max == 0 or (min == 0 and int(value) == 0):
|
1587 |
+
return ''
|
1588 |
+
while len(value) > min and value[-1] == '0':
|
1589 |
+
value = value[:-1]
|
1590 |
+
return get_decimal_symbol(locale, numbering_system=numbering_system) + value
|
lib/python3.10/site-packages/babel/plural.py
ADDED
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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5 |
+
CLDR Plural support. See UTS #35.
|
6 |
+
|
7 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
8 |
+
:license: BSD, see LICENSE for more details.
|
9 |
+
"""
|
10 |
+
from __future__ import annotations
|
11 |
+
|
12 |
+
import decimal
|
13 |
+
import re
|
14 |
+
from collections.abc import Iterable, Mapping
|
15 |
+
from typing import Any, Callable, Literal
|
16 |
+
|
17 |
+
_plural_tags = ('zero', 'one', 'two', 'few', 'many', 'other')
|
18 |
+
_fallback_tag = 'other'
|
19 |
+
|
20 |
+
|
21 |
+
def extract_operands(source: float | decimal.Decimal) -> tuple[decimal.Decimal | int, int, int, int, int, int, Literal[0], Literal[0]]:
|
22 |
+
"""Extract operands from a decimal, a float or an int, according to `CLDR rules`_.
|
23 |
+
|
24 |
+
The result is an 8-tuple (n, i, v, w, f, t, c, e), where those symbols are as follows:
|
25 |
+
|
26 |
+
====== ===============================================================
|
27 |
+
Symbol Value
|
28 |
+
------ ---------------------------------------------------------------
|
29 |
+
n absolute value of the source number (integer and decimals).
|
30 |
+
i integer digits of n.
|
31 |
+
v number of visible fraction digits in n, with trailing zeros.
|
32 |
+
w number of visible fraction digits in n, without trailing zeros.
|
33 |
+
f visible fractional digits in n, with trailing zeros.
|
34 |
+
t visible fractional digits in n, without trailing zeros.
|
35 |
+
c compact decimal exponent value: exponent of the power of 10 used in compact decimal formatting.
|
36 |
+
e currently, synonym for ‘c’. however, may be redefined in the future.
|
37 |
+
====== ===============================================================
|
38 |
+
|
39 |
+
.. _`CLDR rules`: https://www.unicode.org/reports/tr35/tr35-61/tr35-numbers.html#Operands
|
40 |
+
|
41 |
+
:param source: A real number
|
42 |
+
:type source: int|float|decimal.Decimal
|
43 |
+
:return: A n-i-v-w-f-t-c-e tuple
|
44 |
+
:rtype: tuple[decimal.Decimal, int, int, int, int, int, int, int]
|
45 |
+
"""
|
46 |
+
n = abs(source)
|
47 |
+
i = int(n)
|
48 |
+
if isinstance(n, float):
|
49 |
+
if i == n:
|
50 |
+
n = i
|
51 |
+
else:
|
52 |
+
# Cast the `float` to a number via the string representation.
|
53 |
+
# This is required for Python 2.6 anyway (it will straight out fail to
|
54 |
+
# do the conversion otherwise), and it's highly unlikely that the user
|
55 |
+
# actually wants the lossless conversion behavior (quoting the Python
|
56 |
+
# documentation):
|
57 |
+
# > If value is a float, the binary floating point value is losslessly
|
58 |
+
# > converted to its exact decimal equivalent.
|
59 |
+
# > This conversion can often require 53 or more digits of precision.
|
60 |
+
# Should the user want that behavior, they can simply pass in a pre-
|
61 |
+
# converted `Decimal` instance of desired accuracy.
|
62 |
+
n = decimal.Decimal(str(n))
|
63 |
+
|
64 |
+
if isinstance(n, decimal.Decimal):
|
65 |
+
dec_tuple = n.as_tuple()
|
66 |
+
exp = dec_tuple.exponent
|
67 |
+
fraction_digits = dec_tuple.digits[exp:] if exp < 0 else ()
|
68 |
+
trailing = ''.join(str(d) for d in fraction_digits)
|
69 |
+
no_trailing = trailing.rstrip('0')
|
70 |
+
v = len(trailing)
|
71 |
+
w = len(no_trailing)
|
72 |
+
f = int(trailing or 0)
|
73 |
+
t = int(no_trailing or 0)
|
74 |
+
else:
|
75 |
+
v = w = f = t = 0
|
76 |
+
c = e = 0 # TODO: c and e are not supported
|
77 |
+
return n, i, v, w, f, t, c, e
|
78 |
+
|
79 |
+
|
80 |
+
class PluralRule:
|
81 |
+
"""Represents a set of language pluralization rules. The constructor
|
82 |
+
accepts a list of (tag, expr) tuples or a dict of `CLDR rules`_. The
|
83 |
+
resulting object is callable and accepts one parameter with a positive or
|
84 |
+
negative number (both integer and float) for the number that indicates the
|
85 |
+
plural form for a string and returns the tag for the format:
|
86 |
+
|
87 |
+
>>> rule = PluralRule({'one': 'n is 1'})
|
88 |
+
>>> rule(1)
|
89 |
+
'one'
|
90 |
+
>>> rule(2)
|
91 |
+
'other'
|
92 |
+
|
93 |
+
Currently the CLDR defines these tags: zero, one, two, few, many and
|
94 |
+
other where other is an implicit default. Rules should be mutually
|
95 |
+
exclusive; for a given numeric value, only one rule should apply (i.e.
|
96 |
+
the condition should only be true for one of the plural rule elements.
|
97 |
+
|
98 |
+
.. _`CLDR rules`: https://www.unicode.org/reports/tr35/tr35-33/tr35-numbers.html#Language_Plural_Rules
|
99 |
+
"""
|
100 |
+
|
101 |
+
__slots__ = ('abstract', '_func')
|
102 |
+
|
103 |
+
def __init__(self, rules: Mapping[str, str] | Iterable[tuple[str, str]]) -> None:
|
104 |
+
"""Initialize the rule instance.
|
105 |
+
|
106 |
+
:param rules: a list of ``(tag, expr)``) tuples with the rules
|
107 |
+
conforming to UTS #35 or a dict with the tags as keys
|
108 |
+
and expressions as values.
|
109 |
+
:raise RuleError: if the expression is malformed
|
110 |
+
"""
|
111 |
+
if isinstance(rules, Mapping):
|
112 |
+
rules = rules.items()
|
113 |
+
found = set()
|
114 |
+
self.abstract: list[tuple[str, Any]] = []
|
115 |
+
for key, expr in sorted(rules):
|
116 |
+
if key not in _plural_tags:
|
117 |
+
raise ValueError(f"unknown tag {key!r}")
|
118 |
+
elif key in found:
|
119 |
+
raise ValueError(f"tag {key!r} defined twice")
|
120 |
+
found.add(key)
|
121 |
+
ast = _Parser(expr).ast
|
122 |
+
if ast:
|
123 |
+
self.abstract.append((key, ast))
|
124 |
+
|
125 |
+
def __repr__(self) -> str:
|
126 |
+
rules = self.rules
|
127 |
+
args = ", ".join([f"{tag}: {rules[tag]}" for tag in _plural_tags if tag in rules])
|
128 |
+
return f"<{type(self).__name__} {args!r}>"
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def parse(cls, rules: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> PluralRule:
|
132 |
+
"""Create a `PluralRule` instance for the given rules. If the rules
|
133 |
+
are a `PluralRule` object, that object is returned.
|
134 |
+
|
135 |
+
:param rules: the rules as list or dict, or a `PluralRule` object
|
136 |
+
:raise RuleError: if the expression is malformed
|
137 |
+
"""
|
138 |
+
if isinstance(rules, PluralRule):
|
139 |
+
return rules
|
140 |
+
return cls(rules)
|
141 |
+
|
142 |
+
@property
|
143 |
+
def rules(self) -> Mapping[str, str]:
|
144 |
+
"""The `PluralRule` as a dict of unicode plural rules.
|
145 |
+
|
146 |
+
>>> rule = PluralRule({'one': 'n is 1'})
|
147 |
+
>>> rule.rules
|
148 |
+
{'one': 'n is 1'}
|
149 |
+
"""
|
150 |
+
_compile = _UnicodeCompiler().compile
|
151 |
+
return {tag: _compile(ast) for tag, ast in self.abstract}
|
152 |
+
|
153 |
+
@property
|
154 |
+
def tags(self) -> frozenset[str]:
|
155 |
+
"""A set of explicitly defined tags in this rule. The implicit default
|
156 |
+
``'other'`` rules is not part of this set unless there is an explicit
|
157 |
+
rule for it.
|
158 |
+
"""
|
159 |
+
return frozenset(i[0] for i in self.abstract)
|
160 |
+
|
161 |
+
def __getstate__(self) -> list[tuple[str, Any]]:
|
162 |
+
return self.abstract
|
163 |
+
|
164 |
+
def __setstate__(self, abstract: list[tuple[str, Any]]) -> None:
|
165 |
+
self.abstract = abstract
|
166 |
+
|
167 |
+
def __call__(self, n: float | decimal.Decimal) -> str:
|
168 |
+
if not hasattr(self, '_func'):
|
169 |
+
self._func = to_python(self)
|
170 |
+
return self._func(n)
|
171 |
+
|
172 |
+
|
173 |
+
def to_javascript(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> str:
|
174 |
+
"""Convert a list/dict of rules or a `PluralRule` object into a JavaScript
|
175 |
+
function. This function depends on no external library:
|
176 |
+
|
177 |
+
>>> to_javascript({'one': 'n is 1'})
|
178 |
+
"(function(n) { return (n == 1) ? 'one' : 'other'; })"
|
179 |
+
|
180 |
+
Implementation detail: The function generated will probably evaluate
|
181 |
+
expressions involved into range operations multiple times. This has the
|
182 |
+
advantage that external helper functions are not required and is not a
|
183 |
+
big performance hit for these simple calculations.
|
184 |
+
|
185 |
+
:param rule: the rules as list or dict, or a `PluralRule` object
|
186 |
+
:raise RuleError: if the expression is malformed
|
187 |
+
"""
|
188 |
+
to_js = _JavaScriptCompiler().compile
|
189 |
+
result = ['(function(n) { return ']
|
190 |
+
for tag, ast in PluralRule.parse(rule).abstract:
|
191 |
+
result.append(f"{to_js(ast)} ? {tag!r} : ")
|
192 |
+
result.append('%r; })' % _fallback_tag)
|
193 |
+
return ''.join(result)
|
194 |
+
|
195 |
+
|
196 |
+
def to_python(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> Callable[[float | decimal.Decimal], str]:
|
197 |
+
"""Convert a list/dict of rules or a `PluralRule` object into a regular
|
198 |
+
Python function. This is useful in situations where you need a real
|
199 |
+
function and don't are about the actual rule object:
|
200 |
+
|
201 |
+
>>> func = to_python({'one': 'n is 1', 'few': 'n in 2..4'})
|
202 |
+
>>> func(1)
|
203 |
+
'one'
|
204 |
+
>>> func(3)
|
205 |
+
'few'
|
206 |
+
>>> func = to_python({'one': 'n in 1,11', 'few': 'n in 3..10,13..19'})
|
207 |
+
>>> func(11)
|
208 |
+
'one'
|
209 |
+
>>> func(15)
|
210 |
+
'few'
|
211 |
+
|
212 |
+
:param rule: the rules as list or dict, or a `PluralRule` object
|
213 |
+
:raise RuleError: if the expression is malformed
|
214 |
+
"""
|
215 |
+
namespace = {
|
216 |
+
'IN': in_range_list,
|
217 |
+
'WITHIN': within_range_list,
|
218 |
+
'MOD': cldr_modulo,
|
219 |
+
'extract_operands': extract_operands,
|
220 |
+
}
|
221 |
+
to_python_func = _PythonCompiler().compile
|
222 |
+
result = [
|
223 |
+
'def evaluate(n):',
|
224 |
+
' n, i, v, w, f, t, c, e = extract_operands(n)',
|
225 |
+
]
|
226 |
+
for tag, ast in PluralRule.parse(rule).abstract:
|
227 |
+
# the str() call is to coerce the tag to the native string. It's
|
228 |
+
# a limited ascii restricted set of tags anyways so that is fine.
|
229 |
+
result.append(f" if ({to_python_func(ast)}): return {str(tag)!r}")
|
230 |
+
result.append(f" return {_fallback_tag!r}")
|
231 |
+
code = compile('\n'.join(result), '<rule>', 'exec')
|
232 |
+
eval(code, namespace)
|
233 |
+
return namespace['evaluate']
|
234 |
+
|
235 |
+
|
236 |
+
def to_gettext(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> str:
|
237 |
+
"""The plural rule as gettext expression. The gettext expression is
|
238 |
+
technically limited to integers and returns indices rather than tags.
|
239 |
+
|
240 |
+
>>> to_gettext({'one': 'n is 1', 'two': 'n is 2'})
|
241 |
+
'nplurals=3; plural=((n == 1) ? 0 : (n == 2) ? 1 : 2);'
|
242 |
+
|
243 |
+
:param rule: the rules as list or dict, or a `PluralRule` object
|
244 |
+
:raise RuleError: if the expression is malformed
|
245 |
+
"""
|
246 |
+
rule = PluralRule.parse(rule)
|
247 |
+
|
248 |
+
used_tags = rule.tags | {_fallback_tag}
|
249 |
+
_compile = _GettextCompiler().compile
|
250 |
+
_get_index = [tag for tag in _plural_tags if tag in used_tags].index
|
251 |
+
|
252 |
+
result = [f"nplurals={len(used_tags)}; plural=("]
|
253 |
+
for tag, ast in rule.abstract:
|
254 |
+
result.append(f"{_compile(ast)} ? {_get_index(tag)} : ")
|
255 |
+
result.append(f"{_get_index(_fallback_tag)});")
|
256 |
+
return ''.join(result)
|
257 |
+
|
258 |
+
|
259 |
+
def in_range_list(num: float | decimal.Decimal, range_list: Iterable[Iterable[float | decimal.Decimal]]) -> bool:
|
260 |
+
"""Integer range list test. This is the callback for the "in" operator
|
261 |
+
of the UTS #35 pluralization rule language:
|
262 |
+
|
263 |
+
>>> in_range_list(1, [(1, 3)])
|
264 |
+
True
|
265 |
+
>>> in_range_list(3, [(1, 3)])
|
266 |
+
True
|
267 |
+
>>> in_range_list(3, [(1, 3), (5, 8)])
|
268 |
+
True
|
269 |
+
>>> in_range_list(1.2, [(1, 4)])
|
270 |
+
False
|
271 |
+
>>> in_range_list(10, [(1, 4)])
|
272 |
+
False
|
273 |
+
>>> in_range_list(10, [(1, 4), (6, 8)])
|
274 |
+
False
|
275 |
+
"""
|
276 |
+
return num == int(num) and within_range_list(num, range_list)
|
277 |
+
|
278 |
+
|
279 |
+
def within_range_list(num: float | decimal.Decimal, range_list: Iterable[Iterable[float | decimal.Decimal]]) -> bool:
|
280 |
+
"""Float range test. This is the callback for the "within" operator
|
281 |
+
of the UTS #35 pluralization rule language:
|
282 |
+
|
283 |
+
>>> within_range_list(1, [(1, 3)])
|
284 |
+
True
|
285 |
+
>>> within_range_list(1.0, [(1, 3)])
|
286 |
+
True
|
287 |
+
>>> within_range_list(1.2, [(1, 4)])
|
288 |
+
True
|
289 |
+
>>> within_range_list(8.8, [(1, 4), (7, 15)])
|
290 |
+
True
|
291 |
+
>>> within_range_list(10, [(1, 4)])
|
292 |
+
False
|
293 |
+
>>> within_range_list(10.5, [(1, 4), (20, 30)])
|
294 |
+
False
|
295 |
+
"""
|
296 |
+
return any(min_ <= num <= max_ for min_, max_ in range_list)
|
297 |
+
|
298 |
+
|
299 |
+
def cldr_modulo(a: float, b: float) -> float:
|
300 |
+
"""Javaish modulo. This modulo operator returns the value with the sign
|
301 |
+
of the dividend rather than the divisor like Python does:
|
302 |
+
|
303 |
+
>>> cldr_modulo(-3, 5)
|
304 |
+
-3
|
305 |
+
>>> cldr_modulo(-3, -5)
|
306 |
+
-3
|
307 |
+
>>> cldr_modulo(3, 5)
|
308 |
+
3
|
309 |
+
"""
|
310 |
+
reverse = 0
|
311 |
+
if a < 0:
|
312 |
+
a *= -1
|
313 |
+
reverse = 1
|
314 |
+
if b < 0:
|
315 |
+
b *= -1
|
316 |
+
rv = a % b
|
317 |
+
if reverse:
|
318 |
+
rv *= -1
|
319 |
+
return rv
|
320 |
+
|
321 |
+
|
322 |
+
class RuleError(Exception):
|
323 |
+
"""Raised if a rule is malformed."""
|
324 |
+
|
325 |
+
|
326 |
+
_VARS = {
|
327 |
+
'n', # absolute value of the source number.
|
328 |
+
'i', # integer digits of n.
|
329 |
+
'v', # number of visible fraction digits in n, with trailing zeros.*
|
330 |
+
'w', # number of visible fraction digits in n, without trailing zeros.*
|
331 |
+
'f', # visible fraction digits in n, with trailing zeros.*
|
332 |
+
't', # visible fraction digits in n, without trailing zeros.*
|
333 |
+
'c', # compact decimal exponent value: exponent of the power of 10 used in compact decimal formatting.
|
334 |
+
'e', # currently, synonym for `c`. however, may be redefined in the future.
|
335 |
+
}
|
336 |
+
|
337 |
+
_RULES: list[tuple[str | None, re.Pattern[str]]] = [
|
338 |
+
(None, re.compile(r'\s+', re.UNICODE)),
|
339 |
+
('word', re.compile(fr'\b(and|or|is|(?:with)?in|not|mod|[{"".join(_VARS)}])\b')),
|
340 |
+
('value', re.compile(r'\d+')),
|
341 |
+
('symbol', re.compile(r'%|,|!=|=')),
|
342 |
+
('ellipsis', re.compile(r'\.{2,3}|\u2026', re.UNICODE)), # U+2026: ELLIPSIS
|
343 |
+
]
|
344 |
+
|
345 |
+
|
346 |
+
def tokenize_rule(s: str) -> list[tuple[str, str]]:
|
347 |
+
s = s.split('@')[0]
|
348 |
+
result: list[tuple[str, str]] = []
|
349 |
+
pos = 0
|
350 |
+
end = len(s)
|
351 |
+
while pos < end:
|
352 |
+
for tok, rule in _RULES:
|
353 |
+
match = rule.match(s, pos)
|
354 |
+
if match is not None:
|
355 |
+
pos = match.end()
|
356 |
+
if tok:
|
357 |
+
result.append((tok, match.group()))
|
358 |
+
break
|
359 |
+
else:
|
360 |
+
raise RuleError(f"malformed CLDR pluralization rule. Got unexpected {s[pos]!r}")
|
361 |
+
return result[::-1]
|
362 |
+
|
363 |
+
|
364 |
+
def test_next_token(
|
365 |
+
tokens: list[tuple[str, str]],
|
366 |
+
type_: str,
|
367 |
+
value: str | None = None,
|
368 |
+
) -> list[tuple[str, str]] | bool:
|
369 |
+
return tokens and tokens[-1][0] == type_ and \
|
370 |
+
(value is None or tokens[-1][1] == value)
|
371 |
+
|
372 |
+
|
373 |
+
def skip_token(tokens: list[tuple[str, str]], type_: str, value: str | None = None):
|
374 |
+
if test_next_token(tokens, type_, value):
|
375 |
+
return tokens.pop()
|
376 |
+
|
377 |
+
|
378 |
+
def value_node(value: int) -> tuple[Literal['value'], tuple[int]]:
|
379 |
+
return 'value', (value, )
|
380 |
+
|
381 |
+
|
382 |
+
def ident_node(name: str) -> tuple[str, tuple[()]]:
|
383 |
+
return name, ()
|
384 |
+
|
385 |
+
|
386 |
+
def range_list_node(
|
387 |
+
range_list: Iterable[Iterable[float | decimal.Decimal]],
|
388 |
+
) -> tuple[Literal['range_list'], Iterable[Iterable[float | decimal.Decimal]]]:
|
389 |
+
return 'range_list', range_list
|
390 |
+
|
391 |
+
|
392 |
+
def negate(rv: tuple[Any, ...]) -> tuple[Literal['not'], tuple[tuple[Any, ...]]]:
|
393 |
+
return 'not', (rv,)
|
394 |
+
|
395 |
+
|
396 |
+
class _Parser:
|
397 |
+
"""Internal parser. This class can translate a single rule into an abstract
|
398 |
+
tree of tuples. It implements the following grammar::
|
399 |
+
|
400 |
+
condition = and_condition ('or' and_condition)*
|
401 |
+
('@integer' samples)?
|
402 |
+
('@decimal' samples)?
|
403 |
+
and_condition = relation ('and' relation)*
|
404 |
+
relation = is_relation | in_relation | within_relation
|
405 |
+
is_relation = expr 'is' ('not')? value
|
406 |
+
in_relation = expr (('not')? 'in' | '=' | '!=') range_list
|
407 |
+
within_relation = expr ('not')? 'within' range_list
|
408 |
+
expr = operand (('mod' | '%') value)?
|
409 |
+
operand = 'n' | 'i' | 'f' | 't' | 'v' | 'w'
|
410 |
+
range_list = (range | value) (',' range_list)*
|
411 |
+
value = digit+
|
412 |
+
digit = 0|1|2|3|4|5|6|7|8|9
|
413 |
+
range = value'..'value
|
414 |
+
samples = sampleRange (',' sampleRange)* (',' ('…'|'...'))?
|
415 |
+
sampleRange = decimalValue '~' decimalValue
|
416 |
+
decimalValue = value ('.' value)?
|
417 |
+
|
418 |
+
- Whitespace can occur between or around any of the above tokens.
|
419 |
+
- Rules should be mutually exclusive; for a given numeric value, only one
|
420 |
+
rule should apply (i.e. the condition should only be true for one of
|
421 |
+
the plural rule elements).
|
422 |
+
- The in and within relations can take comma-separated lists, such as:
|
423 |
+
'n in 3,5,7..15'.
|
424 |
+
- Samples are ignored.
|
425 |
+
|
426 |
+
The translator parses the expression on instantiation into an attribute
|
427 |
+
called `ast`.
|
428 |
+
"""
|
429 |
+
|
430 |
+
def __init__(self, string):
|
431 |
+
self.tokens = tokenize_rule(string)
|
432 |
+
if not self.tokens:
|
433 |
+
# If the pattern is only samples, it's entirely possible
|
434 |
+
# no stream of tokens whatsoever is generated.
|
435 |
+
self.ast = None
|
436 |
+
return
|
437 |
+
self.ast = self.condition()
|
438 |
+
if self.tokens:
|
439 |
+
raise RuleError(f"Expected end of rule, got {self.tokens[-1][1]!r}")
|
440 |
+
|
441 |
+
def expect(self, type_, value=None, term=None):
|
442 |
+
token = skip_token(self.tokens, type_, value)
|
443 |
+
if token is not None:
|
444 |
+
return token
|
445 |
+
if term is None:
|
446 |
+
term = repr(value is None and type_ or value)
|
447 |
+
if not self.tokens:
|
448 |
+
raise RuleError(f"expected {term} but end of rule reached")
|
449 |
+
raise RuleError(f"expected {term} but got {self.tokens[-1][1]!r}")
|
450 |
+
|
451 |
+
def condition(self):
|
452 |
+
op = self.and_condition()
|
453 |
+
while skip_token(self.tokens, 'word', 'or'):
|
454 |
+
op = 'or', (op, self.and_condition())
|
455 |
+
return op
|
456 |
+
|
457 |
+
def and_condition(self):
|
458 |
+
op = self.relation()
|
459 |
+
while skip_token(self.tokens, 'word', 'and'):
|
460 |
+
op = 'and', (op, self.relation())
|
461 |
+
return op
|
462 |
+
|
463 |
+
def relation(self):
|
464 |
+
left = self.expr()
|
465 |
+
if skip_token(self.tokens, 'word', 'is'):
|
466 |
+
return skip_token(self.tokens, 'word', 'not') and 'isnot' or 'is', \
|
467 |
+
(left, self.value())
|
468 |
+
negated = skip_token(self.tokens, 'word', 'not')
|
469 |
+
method = 'in'
|
470 |
+
if skip_token(self.tokens, 'word', 'within'):
|
471 |
+
method = 'within'
|
472 |
+
else:
|
473 |
+
if not skip_token(self.tokens, 'word', 'in'):
|
474 |
+
if negated:
|
475 |
+
raise RuleError('Cannot negate operator based rules.')
|
476 |
+
return self.newfangled_relation(left)
|
477 |
+
rv = 'relation', (method, left, self.range_list())
|
478 |
+
return negate(rv) if negated else rv
|
479 |
+
|
480 |
+
def newfangled_relation(self, left):
|
481 |
+
if skip_token(self.tokens, 'symbol', '='):
|
482 |
+
negated = False
|
483 |
+
elif skip_token(self.tokens, 'symbol', '!='):
|
484 |
+
negated = True
|
485 |
+
else:
|
486 |
+
raise RuleError('Expected "=" or "!=" or legacy relation')
|
487 |
+
rv = 'relation', ('in', left, self.range_list())
|
488 |
+
return negate(rv) if negated else rv
|
489 |
+
|
490 |
+
def range_or_value(self):
|
491 |
+
left = self.value()
|
492 |
+
if skip_token(self.tokens, 'ellipsis'):
|
493 |
+
return left, self.value()
|
494 |
+
else:
|
495 |
+
return left, left
|
496 |
+
|
497 |
+
def range_list(self):
|
498 |
+
range_list = [self.range_or_value()]
|
499 |
+
while skip_token(self.tokens, 'symbol', ','):
|
500 |
+
range_list.append(self.range_or_value())
|
501 |
+
return range_list_node(range_list)
|
502 |
+
|
503 |
+
def expr(self):
|
504 |
+
word = skip_token(self.tokens, 'word')
|
505 |
+
if word is None or word[1] not in _VARS:
|
506 |
+
raise RuleError('Expected identifier variable')
|
507 |
+
name = word[1]
|
508 |
+
if skip_token(self.tokens, 'word', 'mod'):
|
509 |
+
return 'mod', ((name, ()), self.value())
|
510 |
+
elif skip_token(self.tokens, 'symbol', '%'):
|
511 |
+
return 'mod', ((name, ()), self.value())
|
512 |
+
return ident_node(name)
|
513 |
+
|
514 |
+
def value(self):
|
515 |
+
return value_node(int(self.expect('value')[1]))
|
516 |
+
|
517 |
+
|
518 |
+
def _binary_compiler(tmpl):
|
519 |
+
"""Compiler factory for the `_Compiler`."""
|
520 |
+
return lambda self, left, right: tmpl % (self.compile(left), self.compile(right))
|
521 |
+
|
522 |
+
|
523 |
+
def _unary_compiler(tmpl):
|
524 |
+
"""Compiler factory for the `_Compiler`."""
|
525 |
+
return lambda self, x: tmpl % self.compile(x)
|
526 |
+
|
527 |
+
|
528 |
+
compile_zero = lambda x: '0'
|
529 |
+
|
530 |
+
|
531 |
+
class _Compiler:
|
532 |
+
"""The compilers are able to transform the expressions into multiple
|
533 |
+
output formats.
|
534 |
+
"""
|
535 |
+
|
536 |
+
def compile(self, arg):
|
537 |
+
op, args = arg
|
538 |
+
return getattr(self, f"compile_{op}")(*args)
|
539 |
+
|
540 |
+
compile_n = lambda x: 'n'
|
541 |
+
compile_i = lambda x: 'i'
|
542 |
+
compile_v = lambda x: 'v'
|
543 |
+
compile_w = lambda x: 'w'
|
544 |
+
compile_f = lambda x: 'f'
|
545 |
+
compile_t = lambda x: 't'
|
546 |
+
compile_c = lambda x: 'c'
|
547 |
+
compile_e = lambda x: 'e'
|
548 |
+
compile_value = lambda x, v: str(v)
|
549 |
+
compile_and = _binary_compiler('(%s && %s)')
|
550 |
+
compile_or = _binary_compiler('(%s || %s)')
|
551 |
+
compile_not = _unary_compiler('(!%s)')
|
552 |
+
compile_mod = _binary_compiler('(%s %% %s)')
|
553 |
+
compile_is = _binary_compiler('(%s == %s)')
|
554 |
+
compile_isnot = _binary_compiler('(%s != %s)')
|
555 |
+
|
556 |
+
def compile_relation(self, method, expr, range_list):
|
557 |
+
raise NotImplementedError()
|
558 |
+
|
559 |
+
|
560 |
+
class _PythonCompiler(_Compiler):
|
561 |
+
"""Compiles an expression to Python."""
|
562 |
+
|
563 |
+
compile_and = _binary_compiler('(%s and %s)')
|
564 |
+
compile_or = _binary_compiler('(%s or %s)')
|
565 |
+
compile_not = _unary_compiler('(not %s)')
|
566 |
+
compile_mod = _binary_compiler('MOD(%s, %s)')
|
567 |
+
|
568 |
+
def compile_relation(self, method, expr, range_list):
|
569 |
+
ranges = ",".join([f"({self.compile(a)}, {self.compile(b)})" for (a, b) in range_list[1]])
|
570 |
+
return f"{method.upper()}({self.compile(expr)}, [{ranges}])"
|
571 |
+
|
572 |
+
|
573 |
+
class _GettextCompiler(_Compiler):
|
574 |
+
"""Compile into a gettext plural expression."""
|
575 |
+
|
576 |
+
compile_i = _Compiler.compile_n
|
577 |
+
compile_v = compile_zero
|
578 |
+
compile_w = compile_zero
|
579 |
+
compile_f = compile_zero
|
580 |
+
compile_t = compile_zero
|
581 |
+
|
582 |
+
def compile_relation(self, method, expr, range_list):
|
583 |
+
rv = []
|
584 |
+
expr = self.compile(expr)
|
585 |
+
for item in range_list[1]:
|
586 |
+
if item[0] == item[1]:
|
587 |
+
rv.append(f"({expr} == {self.compile(item[0])})")
|
588 |
+
else:
|
589 |
+
min, max = map(self.compile, item)
|
590 |
+
rv.append(f"({expr} >= {min} && {expr} <= {max})")
|
591 |
+
return f"({' || '.join(rv)})"
|
592 |
+
|
593 |
+
|
594 |
+
class _JavaScriptCompiler(_GettextCompiler):
|
595 |
+
"""Compiles the expression to plain of JavaScript."""
|
596 |
+
|
597 |
+
# XXX: presently javascript does not support any of the
|
598 |
+
# fraction support and basically only deals with integers.
|
599 |
+
compile_i = lambda x: 'parseInt(n, 10)'
|
600 |
+
compile_v = compile_zero
|
601 |
+
compile_w = compile_zero
|
602 |
+
compile_f = compile_zero
|
603 |
+
compile_t = compile_zero
|
604 |
+
|
605 |
+
def compile_relation(self, method, expr, range_list):
|
606 |
+
code = _GettextCompiler.compile_relation(
|
607 |
+
self, method, expr, range_list)
|
608 |
+
if method == 'in':
|
609 |
+
expr = self.compile(expr)
|
610 |
+
code = f"(parseInt({expr}, 10) == {expr} && {code})"
|
611 |
+
return code
|
612 |
+
|
613 |
+
|
614 |
+
class _UnicodeCompiler(_Compiler):
|
615 |
+
"""Returns a unicode pluralization rule again."""
|
616 |
+
|
617 |
+
# XXX: this currently spits out the old syntax instead of the new
|
618 |
+
# one. We can change that, but it will break a whole bunch of stuff
|
619 |
+
# for users I suppose.
|
620 |
+
|
621 |
+
compile_is = _binary_compiler('%s is %s')
|
622 |
+
compile_isnot = _binary_compiler('%s is not %s')
|
623 |
+
compile_and = _binary_compiler('%s and %s')
|
624 |
+
compile_or = _binary_compiler('%s or %s')
|
625 |
+
compile_mod = _binary_compiler('%s mod %s')
|
626 |
+
|
627 |
+
def compile_not(self, relation):
|
628 |
+
return self.compile_relation(*relation[1], negated=True)
|
629 |
+
|
630 |
+
def compile_relation(self, method, expr, range_list, negated=False):
|
631 |
+
ranges = []
|
632 |
+
for item in range_list[1]:
|
633 |
+
if item[0] == item[1]:
|
634 |
+
ranges.append(self.compile(item[0]))
|
635 |
+
else:
|
636 |
+
ranges.append(f"{self.compile(item[0])}..{self.compile(item[1])}")
|
637 |
+
return f"{self.compile(expr)}{' not' if negated else ''} {method} {','.join(ranges)}"
|
lib/python3.10/site-packages/babel/py.typed
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# Marker file for PEP 561. This package uses inline types.
|
lib/python3.10/site-packages/babel/support.py
ADDED
@@ -0,0 +1,726 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
babel.support
|
3 |
+
~~~~~~~~~~~~~
|
4 |
+
|
5 |
+
Several classes and functions that help with integrating and using Babel
|
6 |
+
in applications.
|
7 |
+
|
8 |
+
.. note: the code in this module is not used by Babel itself
|
9 |
+
|
10 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
11 |
+
:license: BSD, see LICENSE for more details.
|
12 |
+
"""
|
13 |
+
from __future__ import annotations
|
14 |
+
|
15 |
+
import gettext
|
16 |
+
import locale
|
17 |
+
import os
|
18 |
+
from collections.abc import Iterator
|
19 |
+
from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal
|
20 |
+
|
21 |
+
from babel.core import Locale
|
22 |
+
from babel.dates import format_date, format_datetime, format_time, format_timedelta
|
23 |
+
from babel.numbers import (
|
24 |
+
format_compact_currency,
|
25 |
+
format_compact_decimal,
|
26 |
+
format_currency,
|
27 |
+
format_decimal,
|
28 |
+
format_percent,
|
29 |
+
format_scientific,
|
30 |
+
)
|
31 |
+
|
32 |
+
if TYPE_CHECKING:
|
33 |
+
import datetime as _datetime
|
34 |
+
from decimal import Decimal
|
35 |
+
|
36 |
+
from babel.dates import _PredefinedTimeFormat
|
37 |
+
|
38 |
+
|
39 |
+
class Format:
|
40 |
+
"""Wrapper class providing the various date and number formatting functions
|
41 |
+
bound to a specific locale and time-zone.
|
42 |
+
|
43 |
+
>>> from babel.util import UTC
|
44 |
+
>>> from datetime import date
|
45 |
+
>>> fmt = Format('en_US', UTC)
|
46 |
+
>>> fmt.date(date(2007, 4, 1))
|
47 |
+
u'Apr 1, 2007'
|
48 |
+
>>> fmt.decimal(1.2345)
|
49 |
+
u'1.234'
|
50 |
+
"""
|
51 |
+
|
52 |
+
def __init__(
|
53 |
+
self,
|
54 |
+
locale: Locale | str,
|
55 |
+
tzinfo: _datetime.tzinfo | None = None,
|
56 |
+
*,
|
57 |
+
numbering_system: Literal["default"] | str = "latn",
|
58 |
+
) -> None:
|
59 |
+
"""Initialize the formatter.
|
60 |
+
|
61 |
+
:param locale: the locale identifier or `Locale` instance
|
62 |
+
:param tzinfo: the time-zone info (a `tzinfo` instance or `None`)
|
63 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
64 |
+
The special value "default" will use the default numbering system of the locale.
|
65 |
+
"""
|
66 |
+
self.locale = Locale.parse(locale)
|
67 |
+
self.tzinfo = tzinfo
|
68 |
+
self.numbering_system = numbering_system
|
69 |
+
|
70 |
+
def date(
|
71 |
+
self,
|
72 |
+
date: _datetime.date | None = None,
|
73 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
74 |
+
) -> str:
|
75 |
+
"""Return a date formatted according to the given pattern.
|
76 |
+
|
77 |
+
>>> from datetime import date
|
78 |
+
>>> fmt = Format('en_US')
|
79 |
+
>>> fmt.date(date(2007, 4, 1))
|
80 |
+
u'Apr 1, 2007'
|
81 |
+
"""
|
82 |
+
return format_date(date, format, locale=self.locale)
|
83 |
+
|
84 |
+
def datetime(
|
85 |
+
self,
|
86 |
+
datetime: _datetime.date | None = None,
|
87 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
88 |
+
) -> str:
|
89 |
+
"""Return a date and time formatted according to the given pattern.
|
90 |
+
|
91 |
+
>>> from datetime import datetime
|
92 |
+
>>> from babel.dates import get_timezone
|
93 |
+
>>> fmt = Format('en_US', tzinfo=get_timezone('US/Eastern'))
|
94 |
+
>>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
|
95 |
+
u'Apr 1, 2007, 11:30:00\u202fAM'
|
96 |
+
"""
|
97 |
+
return format_datetime(datetime, format, tzinfo=self.tzinfo, locale=self.locale)
|
98 |
+
|
99 |
+
def time(
|
100 |
+
self,
|
101 |
+
time: _datetime.time | _datetime.datetime | None = None,
|
102 |
+
format: _PredefinedTimeFormat | str = 'medium',
|
103 |
+
) -> str:
|
104 |
+
"""Return a time formatted according to the given pattern.
|
105 |
+
|
106 |
+
>>> from datetime import datetime
|
107 |
+
>>> from babel.dates import get_timezone
|
108 |
+
>>> fmt = Format('en_US', tzinfo=get_timezone('US/Eastern'))
|
109 |
+
>>> fmt.time(datetime(2007, 4, 1, 15, 30))
|
110 |
+
u'11:30:00\u202fAM'
|
111 |
+
"""
|
112 |
+
return format_time(time, format, tzinfo=self.tzinfo, locale=self.locale)
|
113 |
+
|
114 |
+
def timedelta(
|
115 |
+
self,
|
116 |
+
delta: _datetime.timedelta | int,
|
117 |
+
granularity: Literal["year", "month", "week", "day", "hour", "minute", "second"] = "second",
|
118 |
+
threshold: float = 0.85,
|
119 |
+
format: Literal["narrow", "short", "medium", "long"] = "long",
|
120 |
+
add_direction: bool = False,
|
121 |
+
) -> str:
|
122 |
+
"""Return a time delta according to the rules of the given locale.
|
123 |
+
|
124 |
+
>>> from datetime import timedelta
|
125 |
+
>>> fmt = Format('en_US')
|
126 |
+
>>> fmt.timedelta(timedelta(weeks=11))
|
127 |
+
u'3 months'
|
128 |
+
"""
|
129 |
+
return format_timedelta(delta, granularity=granularity,
|
130 |
+
threshold=threshold,
|
131 |
+
format=format, add_direction=add_direction,
|
132 |
+
locale=self.locale)
|
133 |
+
|
134 |
+
def number(self, number: float | Decimal | str) -> str:
|
135 |
+
"""Return an integer number formatted for the locale.
|
136 |
+
|
137 |
+
>>> fmt = Format('en_US')
|
138 |
+
>>> fmt.number(1099)
|
139 |
+
u'1,099'
|
140 |
+
"""
|
141 |
+
return format_decimal(number, locale=self.locale, numbering_system=self.numbering_system)
|
142 |
+
|
143 |
+
def decimal(self, number: float | Decimal | str, format: str | None = None) -> str:
|
144 |
+
"""Return a decimal number formatted for the locale.
|
145 |
+
|
146 |
+
>>> fmt = Format('en_US')
|
147 |
+
>>> fmt.decimal(1.2345)
|
148 |
+
u'1.234'
|
149 |
+
"""
|
150 |
+
return format_decimal(number, format, locale=self.locale, numbering_system=self.numbering_system)
|
151 |
+
|
152 |
+
def compact_decimal(
|
153 |
+
self,
|
154 |
+
number: float | Decimal | str,
|
155 |
+
format_type: Literal['short', 'long'] = 'short',
|
156 |
+
fraction_digits: int = 0,
|
157 |
+
) -> str:
|
158 |
+
"""Return a number formatted in compact form for the locale.
|
159 |
+
|
160 |
+
>>> fmt = Format('en_US')
|
161 |
+
>>> fmt.compact_decimal(123456789)
|
162 |
+
u'123M'
|
163 |
+
>>> fmt.compact_decimal(1234567, format_type='long', fraction_digits=2)
|
164 |
+
'1.23 million'
|
165 |
+
"""
|
166 |
+
return format_compact_decimal(
|
167 |
+
number,
|
168 |
+
format_type=format_type,
|
169 |
+
fraction_digits=fraction_digits,
|
170 |
+
locale=self.locale,
|
171 |
+
numbering_system=self.numbering_system,
|
172 |
+
)
|
173 |
+
|
174 |
+
def currency(self, number: float | Decimal | str, currency: str) -> str:
|
175 |
+
"""Return a number in the given currency formatted for the locale.
|
176 |
+
"""
|
177 |
+
return format_currency(number, currency, locale=self.locale, numbering_system=self.numbering_system)
|
178 |
+
|
179 |
+
def compact_currency(
|
180 |
+
self,
|
181 |
+
number: float | Decimal | str,
|
182 |
+
currency: str,
|
183 |
+
format_type: Literal['short'] = 'short',
|
184 |
+
fraction_digits: int = 0,
|
185 |
+
) -> str:
|
186 |
+
"""Return a number in the given currency formatted for the locale
|
187 |
+
using the compact number format.
|
188 |
+
|
189 |
+
>>> Format('en_US').compact_currency(1234567, "USD", format_type='short', fraction_digits=2)
|
190 |
+
'$1.23M'
|
191 |
+
"""
|
192 |
+
return format_compact_currency(number, currency, format_type=format_type, fraction_digits=fraction_digits,
|
193 |
+
locale=self.locale, numbering_system=self.numbering_system)
|
194 |
+
|
195 |
+
def percent(self, number: float | Decimal | str, format: str | None = None) -> str:
|
196 |
+
"""Return a number formatted as percentage for the locale.
|
197 |
+
|
198 |
+
>>> fmt = Format('en_US')
|
199 |
+
>>> fmt.percent(0.34)
|
200 |
+
u'34%'
|
201 |
+
"""
|
202 |
+
return format_percent(number, format, locale=self.locale, numbering_system=self.numbering_system)
|
203 |
+
|
204 |
+
def scientific(self, number: float | Decimal | str) -> str:
|
205 |
+
"""Return a number formatted using scientific notation for the locale.
|
206 |
+
"""
|
207 |
+
return format_scientific(number, locale=self.locale, numbering_system=self.numbering_system)
|
208 |
+
|
209 |
+
|
210 |
+
class LazyProxy:
|
211 |
+
"""Class for proxy objects that delegate to a specified function to evaluate
|
212 |
+
the actual object.
|
213 |
+
|
214 |
+
>>> def greeting(name='world'):
|
215 |
+
... return 'Hello, %s!' % name
|
216 |
+
>>> lazy_greeting = LazyProxy(greeting, name='Joe')
|
217 |
+
>>> print(lazy_greeting)
|
218 |
+
Hello, Joe!
|
219 |
+
>>> u' ' + lazy_greeting
|
220 |
+
u' Hello, Joe!'
|
221 |
+
>>> u'(%s)' % lazy_greeting
|
222 |
+
u'(Hello, Joe!)'
|
223 |
+
|
224 |
+
This can be used, for example, to implement lazy translation functions that
|
225 |
+
delay the actual translation until the string is actually used. The
|
226 |
+
rationale for such behavior is that the locale of the user may not always
|
227 |
+
be available. In web applications, you only know the locale when processing
|
228 |
+
a request.
|
229 |
+
|
230 |
+
The proxy implementation attempts to be as complete as possible, so that
|
231 |
+
the lazy objects should mostly work as expected, for example for sorting:
|
232 |
+
|
233 |
+
>>> greetings = [
|
234 |
+
... LazyProxy(greeting, 'world'),
|
235 |
+
... LazyProxy(greeting, 'Joe'),
|
236 |
+
... LazyProxy(greeting, 'universe'),
|
237 |
+
... ]
|
238 |
+
>>> greetings.sort()
|
239 |
+
>>> for greeting in greetings:
|
240 |
+
... print(greeting)
|
241 |
+
Hello, Joe!
|
242 |
+
Hello, universe!
|
243 |
+
Hello, world!
|
244 |
+
"""
|
245 |
+
__slots__ = ['_func', '_args', '_kwargs', '_value', '_is_cache_enabled', '_attribute_error']
|
246 |
+
|
247 |
+
if TYPE_CHECKING:
|
248 |
+
_func: Callable[..., Any]
|
249 |
+
_args: tuple[Any, ...]
|
250 |
+
_kwargs: dict[str, Any]
|
251 |
+
_is_cache_enabled: bool
|
252 |
+
_value: Any
|
253 |
+
_attribute_error: AttributeError | None
|
254 |
+
|
255 |
+
def __init__(self, func: Callable[..., Any], *args: Any, enable_cache: bool = True, **kwargs: Any) -> None:
|
256 |
+
# Avoid triggering our own __setattr__ implementation
|
257 |
+
object.__setattr__(self, '_func', func)
|
258 |
+
object.__setattr__(self, '_args', args)
|
259 |
+
object.__setattr__(self, '_kwargs', kwargs)
|
260 |
+
object.__setattr__(self, '_is_cache_enabled', enable_cache)
|
261 |
+
object.__setattr__(self, '_value', None)
|
262 |
+
object.__setattr__(self, '_attribute_error', None)
|
263 |
+
|
264 |
+
@property
|
265 |
+
def value(self) -> Any:
|
266 |
+
if self._value is None:
|
267 |
+
try:
|
268 |
+
value = self._func(*self._args, **self._kwargs)
|
269 |
+
except AttributeError as error:
|
270 |
+
object.__setattr__(self, '_attribute_error', error)
|
271 |
+
raise
|
272 |
+
|
273 |
+
if not self._is_cache_enabled:
|
274 |
+
return value
|
275 |
+
object.__setattr__(self, '_value', value)
|
276 |
+
return self._value
|
277 |
+
|
278 |
+
def __contains__(self, key: object) -> bool:
|
279 |
+
return key in self.value
|
280 |
+
|
281 |
+
def __bool__(self) -> bool:
|
282 |
+
return bool(self.value)
|
283 |
+
|
284 |
+
def __dir__(self) -> list[str]:
|
285 |
+
return dir(self.value)
|
286 |
+
|
287 |
+
def __iter__(self) -> Iterator[Any]:
|
288 |
+
return iter(self.value)
|
289 |
+
|
290 |
+
def __len__(self) -> int:
|
291 |
+
return len(self.value)
|
292 |
+
|
293 |
+
def __str__(self) -> str:
|
294 |
+
return str(self.value)
|
295 |
+
|
296 |
+
def __add__(self, other: object) -> Any:
|
297 |
+
return self.value + other
|
298 |
+
|
299 |
+
def __radd__(self, other: object) -> Any:
|
300 |
+
return other + self.value
|
301 |
+
|
302 |
+
def __mod__(self, other: object) -> Any:
|
303 |
+
return self.value % other
|
304 |
+
|
305 |
+
def __rmod__(self, other: object) -> Any:
|
306 |
+
return other % self.value
|
307 |
+
|
308 |
+
def __mul__(self, other: object) -> Any:
|
309 |
+
return self.value * other
|
310 |
+
|
311 |
+
def __rmul__(self, other: object) -> Any:
|
312 |
+
return other * self.value
|
313 |
+
|
314 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
315 |
+
return self.value(*args, **kwargs)
|
316 |
+
|
317 |
+
def __lt__(self, other: object) -> bool:
|
318 |
+
return self.value < other
|
319 |
+
|
320 |
+
def __le__(self, other: object) -> bool:
|
321 |
+
return self.value <= other
|
322 |
+
|
323 |
+
def __eq__(self, other: object) -> bool:
|
324 |
+
return self.value == other
|
325 |
+
|
326 |
+
def __ne__(self, other: object) -> bool:
|
327 |
+
return self.value != other
|
328 |
+
|
329 |
+
def __gt__(self, other: object) -> bool:
|
330 |
+
return self.value > other
|
331 |
+
|
332 |
+
def __ge__(self, other: object) -> bool:
|
333 |
+
return self.value >= other
|
334 |
+
|
335 |
+
def __delattr__(self, name: str) -> None:
|
336 |
+
delattr(self.value, name)
|
337 |
+
|
338 |
+
def __getattr__(self, name: str) -> Any:
|
339 |
+
if self._attribute_error is not None:
|
340 |
+
raise self._attribute_error
|
341 |
+
return getattr(self.value, name)
|
342 |
+
|
343 |
+
def __setattr__(self, name: str, value: Any) -> None:
|
344 |
+
setattr(self.value, name, value)
|
345 |
+
|
346 |
+
def __delitem__(self, key: Any) -> None:
|
347 |
+
del self.value[key]
|
348 |
+
|
349 |
+
def __getitem__(self, key: Any) -> Any:
|
350 |
+
return self.value[key]
|
351 |
+
|
352 |
+
def __setitem__(self, key: Any, value: Any) -> None:
|
353 |
+
self.value[key] = value
|
354 |
+
|
355 |
+
def __copy__(self) -> LazyProxy:
|
356 |
+
return LazyProxy(
|
357 |
+
self._func,
|
358 |
+
enable_cache=self._is_cache_enabled,
|
359 |
+
*self._args, # noqa: B026
|
360 |
+
**self._kwargs,
|
361 |
+
)
|
362 |
+
|
363 |
+
def __deepcopy__(self, memo: Any) -> LazyProxy:
|
364 |
+
from copy import deepcopy
|
365 |
+
return LazyProxy(
|
366 |
+
deepcopy(self._func, memo),
|
367 |
+
enable_cache=deepcopy(self._is_cache_enabled, memo),
|
368 |
+
*deepcopy(self._args, memo), # noqa: B026
|
369 |
+
**deepcopy(self._kwargs, memo),
|
370 |
+
)
|
371 |
+
|
372 |
+
|
373 |
+
class NullTranslations(gettext.NullTranslations):
|
374 |
+
|
375 |
+
if TYPE_CHECKING:
|
376 |
+
_info: dict[str, str]
|
377 |
+
_fallback: NullTranslations | None
|
378 |
+
|
379 |
+
DEFAULT_DOMAIN = None
|
380 |
+
|
381 |
+
def __init__(self, fp: gettext._TranslationsReader | None = None) -> None:
|
382 |
+
"""Initialize a simple translations class which is not backed by a
|
383 |
+
real catalog. Behaves similar to gettext.NullTranslations but also
|
384 |
+
offers Babel's on *gettext methods (e.g. 'dgettext()').
|
385 |
+
|
386 |
+
:param fp: a file-like object (ignored in this class)
|
387 |
+
"""
|
388 |
+
# These attributes are set by gettext.NullTranslations when a catalog
|
389 |
+
# is parsed (fp != None). Ensure that they are always present because
|
390 |
+
# some *gettext methods (including '.gettext()') rely on the attributes.
|
391 |
+
self._catalog: dict[tuple[str, Any] | str, str] = {}
|
392 |
+
self.plural: Callable[[float | Decimal], int] = lambda n: int(n != 1)
|
393 |
+
super().__init__(fp=fp)
|
394 |
+
self.files = list(filter(None, [getattr(fp, 'name', None)]))
|
395 |
+
self.domain = self.DEFAULT_DOMAIN
|
396 |
+
self._domains: dict[str, NullTranslations] = {}
|
397 |
+
|
398 |
+
def dgettext(self, domain: str, message: str) -> str:
|
399 |
+
"""Like ``gettext()``, but look the message up in the specified
|
400 |
+
domain.
|
401 |
+
"""
|
402 |
+
return self._domains.get(domain, self).gettext(message)
|
403 |
+
|
404 |
+
def ldgettext(self, domain: str, message: str) -> str:
|
405 |
+
"""Like ``lgettext()``, but look the message up in the specified
|
406 |
+
domain.
|
407 |
+
"""
|
408 |
+
import warnings
|
409 |
+
warnings.warn(
|
410 |
+
'ldgettext() is deprecated, use dgettext() instead',
|
411 |
+
DeprecationWarning,
|
412 |
+
stacklevel=2,
|
413 |
+
)
|
414 |
+
return self._domains.get(domain, self).lgettext(message)
|
415 |
+
|
416 |
+
def udgettext(self, domain: str, message: str) -> str:
|
417 |
+
"""Like ``ugettext()``, but look the message up in the specified
|
418 |
+
domain.
|
419 |
+
"""
|
420 |
+
return self._domains.get(domain, self).ugettext(message)
|
421 |
+
# backward compatibility with 0.9
|
422 |
+
dugettext = udgettext
|
423 |
+
|
424 |
+
def dngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
|
425 |
+
"""Like ``ngettext()``, but look the message up in the specified
|
426 |
+
domain.
|
427 |
+
"""
|
428 |
+
return self._domains.get(domain, self).ngettext(singular, plural, num)
|
429 |
+
|
430 |
+
def ldngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
|
431 |
+
"""Like ``lngettext()``, but look the message up in the specified
|
432 |
+
domain.
|
433 |
+
"""
|
434 |
+
import warnings
|
435 |
+
warnings.warn(
|
436 |
+
'ldngettext() is deprecated, use dngettext() instead',
|
437 |
+
DeprecationWarning,
|
438 |
+
stacklevel=2,
|
439 |
+
)
|
440 |
+
return self._domains.get(domain, self).lngettext(singular, plural, num)
|
441 |
+
|
442 |
+
def udngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
|
443 |
+
"""Like ``ungettext()`` but look the message up in the specified
|
444 |
+
domain.
|
445 |
+
"""
|
446 |
+
return self._domains.get(domain, self).ungettext(singular, plural, num)
|
447 |
+
# backward compatibility with 0.9
|
448 |
+
dungettext = udngettext
|
449 |
+
|
450 |
+
# Most of the downwards code, until it gets included in stdlib, from:
|
451 |
+
# https://bugs.python.org/file10036/gettext-pgettext.patch
|
452 |
+
#
|
453 |
+
# The encoding of a msgctxt and a msgid in a .mo file is
|
454 |
+
# msgctxt + "\x04" + msgid (gettext version >= 0.15)
|
455 |
+
CONTEXT_ENCODING = '%s\x04%s'
|
456 |
+
|
457 |
+
def pgettext(self, context: str, message: str) -> str | object:
|
458 |
+
"""Look up the `context` and `message` id in the catalog and return the
|
459 |
+
corresponding message string, as an 8-bit string encoded with the
|
460 |
+
catalog's charset encoding, if known. If there is no entry in the
|
461 |
+
catalog for the `message` id and `context` , and a fallback has been
|
462 |
+
set, the look up is forwarded to the fallback's ``pgettext()``
|
463 |
+
method. Otherwise, the `message` id is returned.
|
464 |
+
"""
|
465 |
+
ctxt_msg_id = self.CONTEXT_ENCODING % (context, message)
|
466 |
+
missing = object()
|
467 |
+
tmsg = self._catalog.get(ctxt_msg_id, missing)
|
468 |
+
if tmsg is missing:
|
469 |
+
tmsg = self._catalog.get((ctxt_msg_id, self.plural(1)), missing)
|
470 |
+
if tmsg is not missing:
|
471 |
+
return tmsg
|
472 |
+
if self._fallback:
|
473 |
+
return self._fallback.pgettext(context, message)
|
474 |
+
return message
|
475 |
+
|
476 |
+
def lpgettext(self, context: str, message: str) -> str | bytes | object:
|
477 |
+
"""Equivalent to ``pgettext()``, but the translation is returned in the
|
478 |
+
preferred system encoding, if no other encoding was explicitly set with
|
479 |
+
``bind_textdomain_codeset()``.
|
480 |
+
"""
|
481 |
+
import warnings
|
482 |
+
warnings.warn(
|
483 |
+
'lpgettext() is deprecated, use pgettext() instead',
|
484 |
+
DeprecationWarning,
|
485 |
+
stacklevel=2,
|
486 |
+
)
|
487 |
+
tmsg = self.pgettext(context, message)
|
488 |
+
encoding = getattr(self, "_output_charset", None) or locale.getpreferredencoding()
|
489 |
+
return tmsg.encode(encoding) if isinstance(tmsg, str) else tmsg
|
490 |
+
|
491 |
+
def npgettext(self, context: str, singular: str, plural: str, num: int) -> str:
|
492 |
+
"""Do a plural-forms lookup of a message id. `singular` is used as the
|
493 |
+
message id for purposes of lookup in the catalog, while `num` is used to
|
494 |
+
determine which plural form to use. The returned message string is an
|
495 |
+
8-bit string encoded with the catalog's charset encoding, if known.
|
496 |
+
|
497 |
+
If the message id for `context` is not found in the catalog, and a
|
498 |
+
fallback is specified, the request is forwarded to the fallback's
|
499 |
+
``npgettext()`` method. Otherwise, when ``num`` is 1 ``singular`` is
|
500 |
+
returned, and ``plural`` is returned in all other cases.
|
501 |
+
"""
|
502 |
+
ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
|
503 |
+
try:
|
504 |
+
tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
|
505 |
+
return tmsg
|
506 |
+
except KeyError:
|
507 |
+
if self._fallback:
|
508 |
+
return self._fallback.npgettext(context, singular, plural, num)
|
509 |
+
if num == 1:
|
510 |
+
return singular
|
511 |
+
else:
|
512 |
+
return plural
|
513 |
+
|
514 |
+
def lnpgettext(self, context: str, singular: str, plural: str, num: int) -> str | bytes:
|
515 |
+
"""Equivalent to ``npgettext()``, but the translation is returned in the
|
516 |
+
preferred system encoding, if no other encoding was explicitly set with
|
517 |
+
``bind_textdomain_codeset()``.
|
518 |
+
"""
|
519 |
+
import warnings
|
520 |
+
warnings.warn(
|
521 |
+
'lnpgettext() is deprecated, use npgettext() instead',
|
522 |
+
DeprecationWarning,
|
523 |
+
stacklevel=2,
|
524 |
+
)
|
525 |
+
ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
|
526 |
+
try:
|
527 |
+
tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
|
528 |
+
encoding = getattr(self, "_output_charset", None) or locale.getpreferredencoding()
|
529 |
+
return tmsg.encode(encoding)
|
530 |
+
except KeyError:
|
531 |
+
if self._fallback:
|
532 |
+
return self._fallback.lnpgettext(context, singular, plural, num)
|
533 |
+
if num == 1:
|
534 |
+
return singular
|
535 |
+
else:
|
536 |
+
return plural
|
537 |
+
|
538 |
+
def upgettext(self, context: str, message: str) -> str:
|
539 |
+
"""Look up the `context` and `message` id in the catalog and return the
|
540 |
+
corresponding message string, as a Unicode string. If there is no entry
|
541 |
+
in the catalog for the `message` id and `context`, and a fallback has
|
542 |
+
been set, the look up is forwarded to the fallback's ``upgettext()``
|
543 |
+
method. Otherwise, the `message` id is returned.
|
544 |
+
"""
|
545 |
+
ctxt_message_id = self.CONTEXT_ENCODING % (context, message)
|
546 |
+
missing = object()
|
547 |
+
tmsg = self._catalog.get(ctxt_message_id, missing)
|
548 |
+
if tmsg is missing:
|
549 |
+
if self._fallback:
|
550 |
+
return self._fallback.upgettext(context, message)
|
551 |
+
return str(message)
|
552 |
+
assert isinstance(tmsg, str)
|
553 |
+
return tmsg
|
554 |
+
|
555 |
+
def unpgettext(self, context: str, singular: str, plural: str, num: int) -> str:
|
556 |
+
"""Do a plural-forms lookup of a message id. `singular` is used as the
|
557 |
+
message id for purposes of lookup in the catalog, while `num` is used to
|
558 |
+
determine which plural form to use. The returned message string is a
|
559 |
+
Unicode string.
|
560 |
+
|
561 |
+
If the message id for `context` is not found in the catalog, and a
|
562 |
+
fallback is specified, the request is forwarded to the fallback's
|
563 |
+
``unpgettext()`` method. Otherwise, when `num` is 1 `singular` is
|
564 |
+
returned, and `plural` is returned in all other cases.
|
565 |
+
"""
|
566 |
+
ctxt_message_id = self.CONTEXT_ENCODING % (context, singular)
|
567 |
+
try:
|
568 |
+
tmsg = self._catalog[(ctxt_message_id, self.plural(num))]
|
569 |
+
except KeyError:
|
570 |
+
if self._fallback:
|
571 |
+
return self._fallback.unpgettext(context, singular, plural, num)
|
572 |
+
tmsg = str(singular) if num == 1 else str(plural)
|
573 |
+
return tmsg
|
574 |
+
|
575 |
+
def dpgettext(self, domain: str, context: str, message: str) -> str | object:
|
576 |
+
"""Like `pgettext()`, but look the message up in the specified
|
577 |
+
`domain`.
|
578 |
+
"""
|
579 |
+
return self._domains.get(domain, self).pgettext(context, message)
|
580 |
+
|
581 |
+
def udpgettext(self, domain: str, context: str, message: str) -> str:
|
582 |
+
"""Like `upgettext()`, but look the message up in the specified
|
583 |
+
`domain`.
|
584 |
+
"""
|
585 |
+
return self._domains.get(domain, self).upgettext(context, message)
|
586 |
+
# backward compatibility with 0.9
|
587 |
+
dupgettext = udpgettext
|
588 |
+
|
589 |
+
def ldpgettext(self, domain: str, context: str, message: str) -> str | bytes | object:
|
590 |
+
"""Equivalent to ``dpgettext()``, but the translation is returned in the
|
591 |
+
preferred system encoding, if no other encoding was explicitly set with
|
592 |
+
``bind_textdomain_codeset()``.
|
593 |
+
"""
|
594 |
+
return self._domains.get(domain, self).lpgettext(context, message)
|
595 |
+
|
596 |
+
def dnpgettext(self, domain: str, context: str, singular: str, plural: str, num: int) -> str:
|
597 |
+
"""Like ``npgettext``, but look the message up in the specified
|
598 |
+
`domain`.
|
599 |
+
"""
|
600 |
+
return self._domains.get(domain, self).npgettext(context, singular,
|
601 |
+
plural, num)
|
602 |
+
|
603 |
+
def udnpgettext(self, domain: str, context: str, singular: str, plural: str, num: int) -> str:
|
604 |
+
"""Like ``unpgettext``, but look the message up in the specified
|
605 |
+
`domain`.
|
606 |
+
"""
|
607 |
+
return self._domains.get(domain, self).unpgettext(context, singular,
|
608 |
+
plural, num)
|
609 |
+
# backward compatibility with 0.9
|
610 |
+
dunpgettext = udnpgettext
|
611 |
+
|
612 |
+
def ldnpgettext(self, domain: str, context: str, singular: str, plural: str, num: int) -> str | bytes:
|
613 |
+
"""Equivalent to ``dnpgettext()``, but the translation is returned in
|
614 |
+
the preferred system encoding, if no other encoding was explicitly set
|
615 |
+
with ``bind_textdomain_codeset()``.
|
616 |
+
"""
|
617 |
+
return self._domains.get(domain, self).lnpgettext(context, singular,
|
618 |
+
plural, num)
|
619 |
+
|
620 |
+
ugettext = gettext.NullTranslations.gettext
|
621 |
+
ungettext = gettext.NullTranslations.ngettext
|
622 |
+
|
623 |
+
|
624 |
+
class Translations(NullTranslations, gettext.GNUTranslations):
|
625 |
+
"""An extended translation catalog class."""
|
626 |
+
|
627 |
+
DEFAULT_DOMAIN = 'messages'
|
628 |
+
|
629 |
+
def __init__(self, fp: gettext._TranslationsReader | None = None, domain: str | None = None):
|
630 |
+
"""Initialize the translations catalog.
|
631 |
+
|
632 |
+
:param fp: the file-like object the translation should be read from
|
633 |
+
:param domain: the message domain (default: 'messages')
|
634 |
+
"""
|
635 |
+
super().__init__(fp=fp)
|
636 |
+
self.domain = domain or self.DEFAULT_DOMAIN
|
637 |
+
|
638 |
+
ugettext = gettext.GNUTranslations.gettext
|
639 |
+
ungettext = gettext.GNUTranslations.ngettext
|
640 |
+
|
641 |
+
@classmethod
|
642 |
+
def load(
|
643 |
+
cls,
|
644 |
+
dirname: str | os.PathLike[str] | None = None,
|
645 |
+
locales: Iterable[str | Locale] | Locale | str | None = None,
|
646 |
+
domain: str | None = None,
|
647 |
+
) -> NullTranslations:
|
648 |
+
"""Load translations from the given directory.
|
649 |
+
|
650 |
+
:param dirname: the directory containing the ``MO`` files
|
651 |
+
:param locales: the list of locales in order of preference (items in
|
652 |
+
this list can be either `Locale` objects or locale
|
653 |
+
strings)
|
654 |
+
:param domain: the message domain (default: 'messages')
|
655 |
+
"""
|
656 |
+
if not domain:
|
657 |
+
domain = cls.DEFAULT_DOMAIN
|
658 |
+
filename = gettext.find(domain, dirname, _locales_to_names(locales))
|
659 |
+
if not filename:
|
660 |
+
return NullTranslations()
|
661 |
+
with open(filename, 'rb') as fp:
|
662 |
+
return cls(fp=fp, domain=domain)
|
663 |
+
|
664 |
+
def __repr__(self) -> str:
|
665 |
+
version = self._info.get('project-id-version')
|
666 |
+
return f'<{type(self).__name__}: "{version}">'
|
667 |
+
|
668 |
+
def add(self, translations: Translations, merge: bool = True):
|
669 |
+
"""Add the given translations to the catalog.
|
670 |
+
|
671 |
+
If the domain of the translations is different than that of the
|
672 |
+
current catalog, they are added as a catalog that is only accessible
|
673 |
+
by the various ``d*gettext`` functions.
|
674 |
+
|
675 |
+
:param translations: the `Translations` instance with the messages to
|
676 |
+
add
|
677 |
+
:param merge: whether translations for message domains that have
|
678 |
+
already been added should be merged with the existing
|
679 |
+
translations
|
680 |
+
"""
|
681 |
+
domain = getattr(translations, 'domain', self.DEFAULT_DOMAIN)
|
682 |
+
if merge and domain == self.domain:
|
683 |
+
return self.merge(translations)
|
684 |
+
|
685 |
+
existing = self._domains.get(domain)
|
686 |
+
if merge and isinstance(existing, Translations):
|
687 |
+
existing.merge(translations)
|
688 |
+
else:
|
689 |
+
translations.add_fallback(self)
|
690 |
+
self._domains[domain] = translations
|
691 |
+
|
692 |
+
return self
|
693 |
+
|
694 |
+
def merge(self, translations: Translations):
|
695 |
+
"""Merge the given translations into the catalog.
|
696 |
+
|
697 |
+
Message translations in the specified catalog override any messages
|
698 |
+
with the same identifier in the existing catalog.
|
699 |
+
|
700 |
+
:param translations: the `Translations` instance with the messages to
|
701 |
+
merge
|
702 |
+
"""
|
703 |
+
if isinstance(translations, gettext.GNUTranslations):
|
704 |
+
self._catalog.update(translations._catalog)
|
705 |
+
if isinstance(translations, Translations):
|
706 |
+
self.files.extend(translations.files)
|
707 |
+
|
708 |
+
return self
|
709 |
+
|
710 |
+
|
711 |
+
def _locales_to_names(
|
712 |
+
locales: Iterable[str | Locale] | Locale | str | None,
|
713 |
+
) -> list[str] | None:
|
714 |
+
"""Normalize a `locales` argument to a list of locale names.
|
715 |
+
|
716 |
+
:param locales: the list of locales in order of preference (items in
|
717 |
+
this list can be either `Locale` objects or locale
|
718 |
+
strings)
|
719 |
+
"""
|
720 |
+
if locales is None:
|
721 |
+
return None
|
722 |
+
if isinstance(locales, Locale):
|
723 |
+
return [str(locales)]
|
724 |
+
if isinstance(locales, str):
|
725 |
+
return [locales]
|
726 |
+
return [str(locale) for locale in locales]
|
lib/python3.10/site-packages/babel/units.py
ADDED
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import decimal
|
4 |
+
from typing import Literal
|
5 |
+
|
6 |
+
from babel.core import Locale
|
7 |
+
from babel.numbers import LC_NUMERIC, format_decimal
|
8 |
+
|
9 |
+
|
10 |
+
class UnknownUnitError(ValueError):
|
11 |
+
def __init__(self, unit: str, locale: Locale) -> None:
|
12 |
+
ValueError.__init__(self, f"{unit} is not a known unit in {locale}")
|
13 |
+
|
14 |
+
|
15 |
+
def get_unit_name(
|
16 |
+
measurement_unit: str,
|
17 |
+
length: Literal['short', 'long', 'narrow'] = 'long',
|
18 |
+
locale: Locale | str | None = None,
|
19 |
+
) -> str | None:
|
20 |
+
"""
|
21 |
+
Get the display name for a measurement unit in the given locale.
|
22 |
+
|
23 |
+
>>> get_unit_name("radian", locale="en")
|
24 |
+
'radians'
|
25 |
+
|
26 |
+
Unknown units will raise exceptions:
|
27 |
+
|
28 |
+
>>> get_unit_name("battery", locale="fi")
|
29 |
+
Traceback (most recent call last):
|
30 |
+
...
|
31 |
+
UnknownUnitError: battery/long is not a known unit/length in fi
|
32 |
+
|
33 |
+
:param measurement_unit: the code of a measurement unit.
|
34 |
+
Known units can be found in the CLDR Unit Validity XML file:
|
35 |
+
https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
|
36 |
+
|
37 |
+
:param length: "short", "long" or "narrow"
|
38 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
39 |
+
:return: The unit display name, or None.
|
40 |
+
"""
|
41 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
42 |
+
unit = _find_unit_pattern(measurement_unit, locale=locale)
|
43 |
+
if not unit:
|
44 |
+
raise UnknownUnitError(unit=measurement_unit, locale=locale)
|
45 |
+
return locale.unit_display_names.get(unit, {}).get(length)
|
46 |
+
|
47 |
+
|
48 |
+
def _find_unit_pattern(unit_id: str, locale: Locale | str | None = None) -> str | None:
|
49 |
+
"""
|
50 |
+
Expand a unit into a qualified form.
|
51 |
+
|
52 |
+
Known units can be found in the CLDR Unit Validity XML file:
|
53 |
+
https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
|
54 |
+
|
55 |
+
>>> _find_unit_pattern("radian", locale="en")
|
56 |
+
'angle-radian'
|
57 |
+
|
58 |
+
Unknown values will return None.
|
59 |
+
|
60 |
+
>>> _find_unit_pattern("horse", locale="en")
|
61 |
+
|
62 |
+
:param unit_id: the code of a measurement unit.
|
63 |
+
:return: A key to the `unit_patterns` mapping, or None.
|
64 |
+
"""
|
65 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
66 |
+
unit_patterns: dict[str, str] = locale._data["unit_patterns"]
|
67 |
+
if unit_id in unit_patterns:
|
68 |
+
return unit_id
|
69 |
+
for unit_pattern in sorted(unit_patterns, key=len):
|
70 |
+
if unit_pattern.endswith(unit_id):
|
71 |
+
return unit_pattern
|
72 |
+
return None
|
73 |
+
|
74 |
+
|
75 |
+
def format_unit(
|
76 |
+
value: str | float | decimal.Decimal,
|
77 |
+
measurement_unit: str,
|
78 |
+
length: Literal['short', 'long', 'narrow'] = 'long',
|
79 |
+
format: str | None = None,
|
80 |
+
locale: Locale | str | None = None,
|
81 |
+
*,
|
82 |
+
numbering_system: Literal["default"] | str = "latn",
|
83 |
+
) -> str:
|
84 |
+
"""Format a value of a given unit.
|
85 |
+
|
86 |
+
Values are formatted according to the locale's usual pluralization rules
|
87 |
+
and number formats.
|
88 |
+
|
89 |
+
>>> format_unit(12, 'length-meter', locale='ro_RO')
|
90 |
+
u'12 metri'
|
91 |
+
>>> format_unit(15.5, 'length-mile', locale='fi_FI')
|
92 |
+
u'15,5 mailia'
|
93 |
+
>>> format_unit(1200, 'pressure-millimeter-ofhg', locale='nb')
|
94 |
+
u'1\\xa0200 millimeter kvikks\\xf8lv'
|
95 |
+
>>> format_unit(270, 'ton', locale='en')
|
96 |
+
u'270 tons'
|
97 |
+
>>> format_unit(1234.5, 'kilogram', locale='ar_EG', numbering_system='default')
|
98 |
+
u'1٬234٫5 كيلوغرام'
|
99 |
+
|
100 |
+
Number formats may be overridden with the ``format`` parameter.
|
101 |
+
|
102 |
+
>>> import decimal
|
103 |
+
>>> format_unit(decimal.Decimal("-42.774"), 'temperature-celsius', 'short', format='#.0', locale='fr')
|
104 |
+
u'-42,8\\u202f\\xb0C'
|
105 |
+
|
106 |
+
The locale's usual pluralization rules are respected.
|
107 |
+
|
108 |
+
>>> format_unit(1, 'length-meter', locale='ro_RO')
|
109 |
+
u'1 metru'
|
110 |
+
>>> format_unit(0, 'length-mile', locale='cy')
|
111 |
+
u'0 mi'
|
112 |
+
>>> format_unit(1, 'length-mile', locale='cy')
|
113 |
+
u'1 filltir'
|
114 |
+
>>> format_unit(3, 'length-mile', locale='cy')
|
115 |
+
u'3 milltir'
|
116 |
+
|
117 |
+
>>> format_unit(15, 'length-horse', locale='fi')
|
118 |
+
Traceback (most recent call last):
|
119 |
+
...
|
120 |
+
UnknownUnitError: length-horse is not a known unit in fi
|
121 |
+
|
122 |
+
.. versionadded:: 2.2.0
|
123 |
+
|
124 |
+
:param value: the value to format. If this is a string, no number formatting will be attempted.
|
125 |
+
:param measurement_unit: the code of a measurement unit.
|
126 |
+
Known units can be found in the CLDR Unit Validity XML file:
|
127 |
+
https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
|
128 |
+
:param length: "short", "long" or "narrow"
|
129 |
+
:param format: An optional format, as accepted by `format_decimal`.
|
130 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
131 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
132 |
+
The special value "default" will use the default numbering system of the locale.
|
133 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
134 |
+
"""
|
135 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
136 |
+
|
137 |
+
q_unit = _find_unit_pattern(measurement_unit, locale=locale)
|
138 |
+
if not q_unit:
|
139 |
+
raise UnknownUnitError(unit=measurement_unit, locale=locale)
|
140 |
+
unit_patterns = locale._data["unit_patterns"][q_unit].get(length, {})
|
141 |
+
|
142 |
+
if isinstance(value, str): # Assume the value is a preformatted singular.
|
143 |
+
formatted_value = value
|
144 |
+
plural_form = "one"
|
145 |
+
else:
|
146 |
+
formatted_value = format_decimal(value, format, locale, numbering_system=numbering_system)
|
147 |
+
plural_form = locale.plural_form(value)
|
148 |
+
|
149 |
+
if plural_form in unit_patterns:
|
150 |
+
return unit_patterns[plural_form].format(formatted_value)
|
151 |
+
|
152 |
+
# Fall back to a somewhat bad representation.
|
153 |
+
# nb: This is marked as no-cover, as the current CLDR seemingly has no way for this to happen.
|
154 |
+
fallback_name = get_unit_name(measurement_unit, length=length, locale=locale) # pragma: no cover
|
155 |
+
return f"{formatted_value} {fallback_name or measurement_unit}" # pragma: no cover
|
156 |
+
|
157 |
+
|
158 |
+
def _find_compound_unit(
|
159 |
+
numerator_unit: str,
|
160 |
+
denominator_unit: str,
|
161 |
+
locale: Locale | str | None = None,
|
162 |
+
) -> str | None:
|
163 |
+
"""
|
164 |
+
Find a predefined compound unit pattern.
|
165 |
+
|
166 |
+
Used internally by format_compound_unit.
|
167 |
+
|
168 |
+
>>> _find_compound_unit("kilometer", "hour", locale="en")
|
169 |
+
'speed-kilometer-per-hour'
|
170 |
+
|
171 |
+
>>> _find_compound_unit("mile", "gallon", locale="en")
|
172 |
+
'consumption-mile-per-gallon'
|
173 |
+
|
174 |
+
If no predefined compound pattern can be found, `None` is returned.
|
175 |
+
|
176 |
+
>>> _find_compound_unit("gallon", "mile", locale="en")
|
177 |
+
|
178 |
+
>>> _find_compound_unit("horse", "purple", locale="en")
|
179 |
+
|
180 |
+
:param numerator_unit: The numerator unit's identifier
|
181 |
+
:param denominator_unit: The denominator unit's identifier
|
182 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
183 |
+
:return: A key to the `unit_patterns` mapping, or None.
|
184 |
+
:rtype: str|None
|
185 |
+
"""
|
186 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
187 |
+
|
188 |
+
# Qualify the numerator and denominator units. This will turn possibly partial
|
189 |
+
# units like "kilometer" or "hour" into actual units like "length-kilometer" and
|
190 |
+
# "duration-hour".
|
191 |
+
|
192 |
+
resolved_numerator_unit = _find_unit_pattern(numerator_unit, locale=locale)
|
193 |
+
resolved_denominator_unit = _find_unit_pattern(denominator_unit, locale=locale)
|
194 |
+
|
195 |
+
# If either was not found, we can't possibly build a suitable compound unit either.
|
196 |
+
if not (resolved_numerator_unit and resolved_denominator_unit):
|
197 |
+
return None
|
198 |
+
|
199 |
+
# Since compound units are named "speed-kilometer-per-hour", we'll have to slice off
|
200 |
+
# the quantities (i.e. "length", "duration") from both qualified units.
|
201 |
+
|
202 |
+
bare_numerator_unit = resolved_numerator_unit.split("-", 1)[-1]
|
203 |
+
bare_denominator_unit = resolved_denominator_unit.split("-", 1)[-1]
|
204 |
+
|
205 |
+
# Now we can try and rebuild a compound unit specifier, then qualify it:
|
206 |
+
|
207 |
+
return _find_unit_pattern(f"{bare_numerator_unit}-per-{bare_denominator_unit}", locale=locale)
|
208 |
+
|
209 |
+
|
210 |
+
def format_compound_unit(
|
211 |
+
numerator_value: str | float | decimal.Decimal,
|
212 |
+
numerator_unit: str | None = None,
|
213 |
+
denominator_value: str | float | decimal.Decimal = 1,
|
214 |
+
denominator_unit: str | None = None,
|
215 |
+
length: Literal["short", "long", "narrow"] = "long",
|
216 |
+
format: str | None = None,
|
217 |
+
locale: Locale | str | None = None,
|
218 |
+
*,
|
219 |
+
numbering_system: Literal["default"] | str = "latn",
|
220 |
+
) -> str | None:
|
221 |
+
"""
|
222 |
+
Format a compound number value, i.e. "kilometers per hour" or similar.
|
223 |
+
|
224 |
+
Both unit specifiers are optional to allow for formatting of arbitrary values still according
|
225 |
+
to the locale's general "per" formatting specifier.
|
226 |
+
|
227 |
+
>>> format_compound_unit(7, denominator_value=11, length="short", locale="pt")
|
228 |
+
'7/11'
|
229 |
+
|
230 |
+
>>> format_compound_unit(150, "kilometer", denominator_unit="hour", locale="sv")
|
231 |
+
'150 kilometer per timme'
|
232 |
+
|
233 |
+
>>> format_compound_unit(150, "kilowatt", denominator_unit="year", locale="fi")
|
234 |
+
'150 kilowattia / vuosi'
|
235 |
+
|
236 |
+
>>> format_compound_unit(32.5, "ton", 15, denominator_unit="hour", locale="en")
|
237 |
+
'32.5 tons per 15 hours'
|
238 |
+
|
239 |
+
>>> format_compound_unit(1234.5, "ton", 15, denominator_unit="hour", locale="ar_EG", numbering_system="arab")
|
240 |
+
'1٬234٫5 طن لكل 15 ساعة'
|
241 |
+
|
242 |
+
>>> format_compound_unit(160, denominator_unit="square-meter", locale="fr")
|
243 |
+
'160 par m\\xe8tre carr\\xe9'
|
244 |
+
|
245 |
+
>>> format_compound_unit(4, "meter", "ratakisko", length="short", locale="fi")
|
246 |
+
'4 m/ratakisko'
|
247 |
+
|
248 |
+
>>> format_compound_unit(35, "minute", denominator_unit="nautical-mile", locale="sv")
|
249 |
+
'35 minuter per nautisk mil'
|
250 |
+
|
251 |
+
>>> from babel.numbers import format_currency
|
252 |
+
>>> format_compound_unit(format_currency(35, "JPY", locale="de"), denominator_unit="liter", locale="de")
|
253 |
+
'35\\xa0\\xa5 pro Liter'
|
254 |
+
|
255 |
+
See https://www.unicode.org/reports/tr35/tr35-general.html#perUnitPatterns
|
256 |
+
|
257 |
+
:param numerator_value: The numerator value. This may be a string,
|
258 |
+
in which case it is considered preformatted and the unit is ignored.
|
259 |
+
:param numerator_unit: The numerator unit. See `format_unit`.
|
260 |
+
:param denominator_value: The denominator value. This may be a string,
|
261 |
+
in which case it is considered preformatted and the unit is ignored.
|
262 |
+
:param denominator_unit: The denominator unit. See `format_unit`.
|
263 |
+
:param length: The formatting length. "short", "long" or "narrow"
|
264 |
+
:param format: An optional format, as accepted by `format_decimal`.
|
265 |
+
:param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
|
266 |
+
:param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
|
267 |
+
The special value "default" will use the default numbering system of the locale.
|
268 |
+
:return: A formatted compound value.
|
269 |
+
:raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
|
270 |
+
"""
|
271 |
+
locale = Locale.parse(locale or LC_NUMERIC)
|
272 |
+
|
273 |
+
# Look for a specific compound unit first...
|
274 |
+
|
275 |
+
if numerator_unit and denominator_unit and denominator_value == 1:
|
276 |
+
compound_unit = _find_compound_unit(numerator_unit, denominator_unit, locale=locale)
|
277 |
+
if compound_unit:
|
278 |
+
return format_unit(
|
279 |
+
numerator_value,
|
280 |
+
compound_unit,
|
281 |
+
length=length,
|
282 |
+
format=format,
|
283 |
+
locale=locale,
|
284 |
+
numbering_system=numbering_system,
|
285 |
+
)
|
286 |
+
|
287 |
+
# ... failing that, construct one "by hand".
|
288 |
+
|
289 |
+
if isinstance(numerator_value, str): # Numerator is preformatted
|
290 |
+
formatted_numerator = numerator_value
|
291 |
+
elif numerator_unit: # Numerator has unit
|
292 |
+
formatted_numerator = format_unit(
|
293 |
+
numerator_value,
|
294 |
+
numerator_unit,
|
295 |
+
length=length,
|
296 |
+
format=format,
|
297 |
+
locale=locale,
|
298 |
+
numbering_system=numbering_system,
|
299 |
+
)
|
300 |
+
else: # Unitless numerator
|
301 |
+
formatted_numerator = format_decimal(
|
302 |
+
numerator_value,
|
303 |
+
format=format,
|
304 |
+
locale=locale,
|
305 |
+
numbering_system=numbering_system,
|
306 |
+
)
|
307 |
+
|
308 |
+
if isinstance(denominator_value, str): # Denominator is preformatted
|
309 |
+
formatted_denominator = denominator_value
|
310 |
+
elif denominator_unit: # Denominator has unit
|
311 |
+
if denominator_value == 1: # support perUnitPatterns when the denominator is 1
|
312 |
+
denominator_unit = _find_unit_pattern(denominator_unit, locale=locale)
|
313 |
+
per_pattern = locale._data["unit_patterns"].get(denominator_unit, {}).get(length, {}).get("per")
|
314 |
+
if per_pattern:
|
315 |
+
return per_pattern.format(formatted_numerator)
|
316 |
+
# See TR-35's per-unit pattern algorithm, point 3.2.
|
317 |
+
# For denominator 1, we replace the value to be formatted with the empty string;
|
318 |
+
# this will make `format_unit` return " second" instead of "1 second".
|
319 |
+
denominator_value = ""
|
320 |
+
|
321 |
+
formatted_denominator = format_unit(
|
322 |
+
denominator_value,
|
323 |
+
measurement_unit=(denominator_unit or ""),
|
324 |
+
length=length,
|
325 |
+
format=format,
|
326 |
+
locale=locale,
|
327 |
+
numbering_system=numbering_system,
|
328 |
+
).strip()
|
329 |
+
else: # Bare denominator
|
330 |
+
formatted_denominator = format_decimal(
|
331 |
+
denominator_value,
|
332 |
+
format=format,
|
333 |
+
locale=locale,
|
334 |
+
numbering_system=numbering_system,
|
335 |
+
)
|
336 |
+
|
337 |
+
# TODO: this doesn't support "compound_variations" (or "prefix"), and will fall back to the "x/y" representation
|
338 |
+
per_pattern = locale._data["compound_unit_patterns"].get("per", {}).get(length, {}).get("compound", "{0}/{1}")
|
339 |
+
|
340 |
+
return per_pattern.format(formatted_numerator, formatted_denominator)
|
lib/python3.10/site-packages/babel/util.py
ADDED
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
~~~~~~~~~~
|
4 |
+
|
5 |
+
Various utility classes and functions.
|
6 |
+
|
7 |
+
:copyright: (c) 2013-2025 by the Babel Team.
|
8 |
+
:license: BSD, see LICENSE for more details.
|
9 |
+
"""
|
10 |
+
from __future__ import annotations
|
11 |
+
|
12 |
+
import codecs
|
13 |
+
import datetime
|
14 |
+
import os
|
15 |
+
import re
|
16 |
+
import textwrap
|
17 |
+
import warnings
|
18 |
+
from collections.abc import Generator, Iterable
|
19 |
+
from typing import IO, Any, TypeVar
|
20 |
+
|
21 |
+
from babel import dates, localtime
|
22 |
+
|
23 |
+
missing = object()
|
24 |
+
|
25 |
+
_T = TypeVar("_T")
|
26 |
+
|
27 |
+
|
28 |
+
def distinct(iterable: Iterable[_T]) -> Generator[_T, None, None]:
|
29 |
+
"""Yield all items in an iterable collection that are distinct.
|
30 |
+
|
31 |
+
Unlike when using sets for a similar effect, the original ordering of the
|
32 |
+
items in the collection is preserved by this function.
|
33 |
+
|
34 |
+
>>> print(list(distinct([1, 2, 1, 3, 4, 4])))
|
35 |
+
[1, 2, 3, 4]
|
36 |
+
>>> print(list(distinct('foobar')))
|
37 |
+
['f', 'o', 'b', 'a', 'r']
|
38 |
+
|
39 |
+
:param iterable: the iterable collection providing the data
|
40 |
+
"""
|
41 |
+
seen = set()
|
42 |
+
for item in iter(iterable):
|
43 |
+
if item not in seen:
|
44 |
+
yield item
|
45 |
+
seen.add(item)
|
46 |
+
|
47 |
+
|
48 |
+
# Regexp to match python magic encoding line
|
49 |
+
PYTHON_MAGIC_COMMENT_re = re.compile(
|
50 |
+
br'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)', re.VERBOSE)
|
51 |
+
|
52 |
+
|
53 |
+
def parse_encoding(fp: IO[bytes]) -> str | None:
|
54 |
+
"""Deduce the encoding of a source file from magic comment.
|
55 |
+
|
56 |
+
It does this in the same way as the `Python interpreter`__
|
57 |
+
|
58 |
+
.. __: https://docs.python.org/3.4/reference/lexical_analysis.html#encoding-declarations
|
59 |
+
|
60 |
+
The ``fp`` argument should be a seekable file object.
|
61 |
+
|
62 |
+
(From Jeff Dairiki)
|
63 |
+
"""
|
64 |
+
pos = fp.tell()
|
65 |
+
fp.seek(0)
|
66 |
+
try:
|
67 |
+
line1 = fp.readline()
|
68 |
+
has_bom = line1.startswith(codecs.BOM_UTF8)
|
69 |
+
if has_bom:
|
70 |
+
line1 = line1[len(codecs.BOM_UTF8):]
|
71 |
+
|
72 |
+
m = PYTHON_MAGIC_COMMENT_re.match(line1)
|
73 |
+
if not m:
|
74 |
+
try:
|
75 |
+
import ast
|
76 |
+
ast.parse(line1.decode('latin-1'))
|
77 |
+
except (ImportError, SyntaxError, UnicodeEncodeError):
|
78 |
+
# Either it's a real syntax error, in which case the source is
|
79 |
+
# not valid python source, or line2 is a continuation of line1,
|
80 |
+
# in which case we don't want to scan line2 for a magic
|
81 |
+
# comment.
|
82 |
+
pass
|
83 |
+
else:
|
84 |
+
line2 = fp.readline()
|
85 |
+
m = PYTHON_MAGIC_COMMENT_re.match(line2)
|
86 |
+
|
87 |
+
if has_bom:
|
88 |
+
if m:
|
89 |
+
magic_comment_encoding = m.group(1).decode('latin-1')
|
90 |
+
if magic_comment_encoding != 'utf-8':
|
91 |
+
raise SyntaxError(f"encoding problem: {magic_comment_encoding} with BOM")
|
92 |
+
return 'utf-8'
|
93 |
+
elif m:
|
94 |
+
return m.group(1).decode('latin-1')
|
95 |
+
else:
|
96 |
+
return None
|
97 |
+
finally:
|
98 |
+
fp.seek(pos)
|
99 |
+
|
100 |
+
|
101 |
+
PYTHON_FUTURE_IMPORT_re = re.compile(
|
102 |
+
r'from\s+__future__\s+import\s+\(*(.+)\)*')
|
103 |
+
|
104 |
+
|
105 |
+
def parse_future_flags(fp: IO[bytes], encoding: str = 'latin-1') -> int:
|
106 |
+
"""Parse the compiler flags by :mod:`__future__` from the given Python
|
107 |
+
code.
|
108 |
+
"""
|
109 |
+
import __future__
|
110 |
+
pos = fp.tell()
|
111 |
+
fp.seek(0)
|
112 |
+
flags = 0
|
113 |
+
try:
|
114 |
+
body = fp.read().decode(encoding)
|
115 |
+
|
116 |
+
# Fix up the source to be (hopefully) parsable by regexpen.
|
117 |
+
# This will likely do untoward things if the source code itself is broken.
|
118 |
+
|
119 |
+
# (1) Fix `import (\n...` to be `import (...`.
|
120 |
+
body = re.sub(r'import\s*\([\r\n]+', 'import (', body)
|
121 |
+
# (2) Join line-ending commas with the next line.
|
122 |
+
body = re.sub(r',\s*[\r\n]+', ', ', body)
|
123 |
+
# (3) Remove backslash line continuations.
|
124 |
+
body = re.sub(r'\\\s*[\r\n]+', ' ', body)
|
125 |
+
|
126 |
+
for m in PYTHON_FUTURE_IMPORT_re.finditer(body):
|
127 |
+
names = [x.strip().strip('()') for x in m.group(1).split(',')]
|
128 |
+
for name in names:
|
129 |
+
feature = getattr(__future__, name, None)
|
130 |
+
if feature:
|
131 |
+
flags |= feature.compiler_flag
|
132 |
+
finally:
|
133 |
+
fp.seek(pos)
|
134 |
+
return flags
|
135 |
+
|
136 |
+
|
137 |
+
def pathmatch(pattern: str, filename: str) -> bool:
|
138 |
+
"""Extended pathname pattern matching.
|
139 |
+
|
140 |
+
This function is similar to what is provided by the ``fnmatch`` module in
|
141 |
+
the Python standard library, but:
|
142 |
+
|
143 |
+
* can match complete (relative or absolute) path names, and not just file
|
144 |
+
names, and
|
145 |
+
* also supports a convenience pattern ("**") to match files at any
|
146 |
+
directory level.
|
147 |
+
|
148 |
+
Examples:
|
149 |
+
|
150 |
+
>>> pathmatch('**.py', 'bar.py')
|
151 |
+
True
|
152 |
+
>>> pathmatch('**.py', 'foo/bar/baz.py')
|
153 |
+
True
|
154 |
+
>>> pathmatch('**.py', 'templates/index.html')
|
155 |
+
False
|
156 |
+
|
157 |
+
>>> pathmatch('./foo/**.py', 'foo/bar/baz.py')
|
158 |
+
True
|
159 |
+
>>> pathmatch('./foo/**.py', 'bar/baz.py')
|
160 |
+
False
|
161 |
+
|
162 |
+
>>> pathmatch('^foo/**.py', 'foo/bar/baz.py')
|
163 |
+
True
|
164 |
+
>>> pathmatch('^foo/**.py', 'bar/baz.py')
|
165 |
+
False
|
166 |
+
|
167 |
+
>>> pathmatch('**/templates/*.html', 'templates/index.html')
|
168 |
+
True
|
169 |
+
>>> pathmatch('**/templates/*.html', 'templates/foo/bar.html')
|
170 |
+
False
|
171 |
+
|
172 |
+
:param pattern: the glob pattern
|
173 |
+
:param filename: the path name of the file to match against
|
174 |
+
"""
|
175 |
+
symbols = {
|
176 |
+
'?': '[^/]',
|
177 |
+
'?/': '[^/]/',
|
178 |
+
'*': '[^/]+',
|
179 |
+
'*/': '[^/]+/',
|
180 |
+
'**/': '(?:.+/)*?',
|
181 |
+
'**': '(?:.+/)*?[^/]+',
|
182 |
+
}
|
183 |
+
|
184 |
+
if pattern.startswith('^'):
|
185 |
+
buf = ['^']
|
186 |
+
pattern = pattern[1:]
|
187 |
+
elif pattern.startswith('./'):
|
188 |
+
buf = ['^']
|
189 |
+
pattern = pattern[2:]
|
190 |
+
else:
|
191 |
+
buf = []
|
192 |
+
|
193 |
+
for idx, part in enumerate(re.split('([?*]+/?)', pattern)):
|
194 |
+
if idx % 2:
|
195 |
+
buf.append(symbols[part])
|
196 |
+
elif part:
|
197 |
+
buf.append(re.escape(part))
|
198 |
+
match = re.match(f"{''.join(buf)}$", filename.replace(os.sep, "/"))
|
199 |
+
return match is not None
|
200 |
+
|
201 |
+
|
202 |
+
class TextWrapper(textwrap.TextWrapper):
|
203 |
+
wordsep_re = re.compile(
|
204 |
+
r'(\s+|' # any whitespace
|
205 |
+
r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))', # em-dash
|
206 |
+
)
|
207 |
+
|
208 |
+
# e.g. '\u2068foo bar.py\u2069:42'
|
209 |
+
_enclosed_filename_re = re.compile(r'(\u2068[^\u2068]+?\u2069(?::-?\d+)?)')
|
210 |
+
|
211 |
+
def _split(self, text):
|
212 |
+
"""Splits the text into indivisible chunks while ensuring that file names
|
213 |
+
containing spaces are not broken up.
|
214 |
+
"""
|
215 |
+
enclosed_filename_start = '\u2068'
|
216 |
+
if enclosed_filename_start not in text:
|
217 |
+
# There are no file names which contain spaces, fallback to the default implementation
|
218 |
+
return super()._split(text)
|
219 |
+
|
220 |
+
chunks = []
|
221 |
+
for chunk in re.split(self._enclosed_filename_re, text):
|
222 |
+
if chunk.startswith(enclosed_filename_start):
|
223 |
+
chunks.append(chunk)
|
224 |
+
else:
|
225 |
+
chunks.extend(super()._split(chunk))
|
226 |
+
return [c for c in chunks if c]
|
227 |
+
|
228 |
+
|
229 |
+
def wraptext(text: str, width: int = 70, initial_indent: str = '', subsequent_indent: str = '') -> list[str]:
|
230 |
+
"""Simple wrapper around the ``textwrap.wrap`` function in the standard
|
231 |
+
library. This version does not wrap lines on hyphens in words. It also
|
232 |
+
does not wrap PO file locations containing spaces.
|
233 |
+
|
234 |
+
:param text: the text to wrap
|
235 |
+
:param width: the maximum line width
|
236 |
+
:param initial_indent: string that will be prepended to the first line of
|
237 |
+
wrapped output
|
238 |
+
:param subsequent_indent: string that will be prepended to all lines save
|
239 |
+
the first of wrapped output
|
240 |
+
"""
|
241 |
+
warnings.warn(
|
242 |
+
"`babel.util.wraptext` is deprecated and will be removed in a future version of Babel. "
|
243 |
+
"If you need this functionality, use the `babel.util.TextWrapper` class directly.",
|
244 |
+
DeprecationWarning,
|
245 |
+
stacklevel=2,
|
246 |
+
)
|
247 |
+
wrapper = TextWrapper(width=width, initial_indent=initial_indent,
|
248 |
+
subsequent_indent=subsequent_indent,
|
249 |
+
break_long_words=False)
|
250 |
+
return wrapper.wrap(text)
|
251 |
+
|
252 |
+
|
253 |
+
# TODO (Babel 3.x): Remove this re-export
|
254 |
+
odict = dict
|
255 |
+
|
256 |
+
|
257 |
+
class FixedOffsetTimezone(datetime.tzinfo):
|
258 |
+
"""Fixed offset in minutes east from UTC."""
|
259 |
+
|
260 |
+
def __init__(self, offset: float, name: str | None = None) -> None:
|
261 |
+
|
262 |
+
self._offset = datetime.timedelta(minutes=offset)
|
263 |
+
if name is None:
|
264 |
+
name = 'Etc/GMT%+d' % offset
|
265 |
+
self.zone = name
|
266 |
+
|
267 |
+
def __str__(self) -> str:
|
268 |
+
return self.zone
|
269 |
+
|
270 |
+
def __repr__(self) -> str:
|
271 |
+
return f'<FixedOffset "{self.zone}" {self._offset}>'
|
272 |
+
|
273 |
+
def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta:
|
274 |
+
return self._offset
|
275 |
+
|
276 |
+
def tzname(self, dt: datetime.datetime) -> str:
|
277 |
+
return self.zone
|
278 |
+
|
279 |
+
def dst(self, dt: datetime.datetime) -> datetime.timedelta:
|
280 |
+
return ZERO
|
281 |
+
|
282 |
+
|
283 |
+
# Export the localtime functionality here because that's
|
284 |
+
# where it was in the past.
|
285 |
+
# TODO(3.0): remove these aliases
|
286 |
+
UTC = dates.UTC
|
287 |
+
LOCALTZ = dates.LOCALTZ
|
288 |
+
get_localzone = localtime.get_localzone
|
289 |
+
STDOFFSET = localtime.STDOFFSET
|
290 |
+
DSTOFFSET = localtime.DSTOFFSET
|
291 |
+
DSTDIFF = localtime.DSTDIFF
|
292 |
+
ZERO = localtime.ZERO
|
293 |
+
|
294 |
+
|
295 |
+
def _cmp(a: Any, b: Any):
|
296 |
+
return (a > b) - (a < b)
|
lib/python3.10/site-packages/colorama/__init__.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console
|
3 |
+
from .ansi import Fore, Back, Style, Cursor
|
4 |
+
from .ansitowin32 import AnsiToWin32
|
5 |
+
|
6 |
+
__version__ = '0.4.6'
|
7 |
+
|
lib/python3.10/site-packages/colorama/ansi.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
'''
|
3 |
+
This module generates ANSI character codes to printing colors to terminals.
|
4 |
+
See: http://en.wikipedia.org/wiki/ANSI_escape_code
|
5 |
+
'''
|
6 |
+
|
7 |
+
CSI = '\033['
|
8 |
+
OSC = '\033]'
|
9 |
+
BEL = '\a'
|
10 |
+
|
11 |
+
|
12 |
+
def code_to_chars(code):
|
13 |
+
return CSI + str(code) + 'm'
|
14 |
+
|
15 |
+
def set_title(title):
|
16 |
+
return OSC + '2;' + title + BEL
|
17 |
+
|
18 |
+
def clear_screen(mode=2):
|
19 |
+
return CSI + str(mode) + 'J'
|
20 |
+
|
21 |
+
def clear_line(mode=2):
|
22 |
+
return CSI + str(mode) + 'K'
|
23 |
+
|
24 |
+
|
25 |
+
class AnsiCodes(object):
|
26 |
+
def __init__(self):
|
27 |
+
# the subclasses declare class attributes which are numbers.
|
28 |
+
# Upon instantiation we define instance attributes, which are the same
|
29 |
+
# as the class attributes but wrapped with the ANSI escape sequence
|
30 |
+
for name in dir(self):
|
31 |
+
if not name.startswith('_'):
|
32 |
+
value = getattr(self, name)
|
33 |
+
setattr(self, name, code_to_chars(value))
|
34 |
+
|
35 |
+
|
36 |
+
class AnsiCursor(object):
|
37 |
+
def UP(self, n=1):
|
38 |
+
return CSI + str(n) + 'A'
|
39 |
+
def DOWN(self, n=1):
|
40 |
+
return CSI + str(n) + 'B'
|
41 |
+
def FORWARD(self, n=1):
|
42 |
+
return CSI + str(n) + 'C'
|
43 |
+
def BACK(self, n=1):
|
44 |
+
return CSI + str(n) + 'D'
|
45 |
+
def POS(self, x=1, y=1):
|
46 |
+
return CSI + str(y) + ';' + str(x) + 'H'
|
47 |
+
|
48 |
+
|
49 |
+
class AnsiFore(AnsiCodes):
|
50 |
+
BLACK = 30
|
51 |
+
RED = 31
|
52 |
+
GREEN = 32
|
53 |
+
YELLOW = 33
|
54 |
+
BLUE = 34
|
55 |
+
MAGENTA = 35
|
56 |
+
CYAN = 36
|
57 |
+
WHITE = 37
|
58 |
+
RESET = 39
|
59 |
+
|
60 |
+
# These are fairly well supported, but not part of the standard.
|
61 |
+
LIGHTBLACK_EX = 90
|
62 |
+
LIGHTRED_EX = 91
|
63 |
+
LIGHTGREEN_EX = 92
|
64 |
+
LIGHTYELLOW_EX = 93
|
65 |
+
LIGHTBLUE_EX = 94
|
66 |
+
LIGHTMAGENTA_EX = 95
|
67 |
+
LIGHTCYAN_EX = 96
|
68 |
+
LIGHTWHITE_EX = 97
|
69 |
+
|
70 |
+
|
71 |
+
class AnsiBack(AnsiCodes):
|
72 |
+
BLACK = 40
|
73 |
+
RED = 41
|
74 |
+
GREEN = 42
|
75 |
+
YELLOW = 43
|
76 |
+
BLUE = 44
|
77 |
+
MAGENTA = 45
|
78 |
+
CYAN = 46
|
79 |
+
WHITE = 47
|
80 |
+
RESET = 49
|
81 |
+
|
82 |
+
# These are fairly well supported, but not part of the standard.
|
83 |
+
LIGHTBLACK_EX = 100
|
84 |
+
LIGHTRED_EX = 101
|
85 |
+
LIGHTGREEN_EX = 102
|
86 |
+
LIGHTYELLOW_EX = 103
|
87 |
+
LIGHTBLUE_EX = 104
|
88 |
+
LIGHTMAGENTA_EX = 105
|
89 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import re
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
|
6 |
+
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
|
7 |
+
from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle
|
8 |
+
from .win32 import windll, winapi_test
|
9 |
+
|
10 |
+
|
11 |
+
winterm = None
|
12 |
+
if windll is not None:
|
13 |
+
winterm = WinTerm()
|
14 |
+
|
15 |
+
|
16 |
+
class StreamWrapper(object):
|
17 |
+
'''
|
18 |
+
Wraps a stream (such as stdout), acting as a transparent proxy for all
|
19 |
+
attribute access apart from method 'write()', which is delegated to our
|
20 |
+
Converter instance.
|
21 |
+
'''
|
22 |
+
def __init__(self, wrapped, converter):
|
23 |
+
# double-underscore everything to prevent clashes with names of
|
24 |
+
# attributes on the wrapped stream object.
|
25 |
+
self.__wrapped = wrapped
|
26 |
+
self.__convertor = converter
|
27 |
+
|
28 |
+
def __getattr__(self, name):
|
29 |
+
return getattr(self.__wrapped, name)
|
30 |
+
|
31 |
+
def __enter__(self, *args, **kwargs):
|
32 |
+
# special method lookup bypasses __getattr__/__getattribute__, see
|
33 |
+
# https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit
|
34 |
+
# thus, contextlib magic methods are not proxied via __getattr__
|
35 |
+
return self.__wrapped.__enter__(*args, **kwargs)
|
36 |
+
|
37 |
+
def __exit__(self, *args, **kwargs):
|
38 |
+
return self.__wrapped.__exit__(*args, **kwargs)
|
39 |
+
|
40 |
+
def __setstate__(self, state):
|
41 |
+
self.__dict__ = state
|
42 |
+
|
43 |
+
def __getstate__(self):
|
44 |
+
return self.__dict__
|
45 |
+
|
46 |
+
def write(self, text):
|
47 |
+
self.__convertor.write(text)
|
48 |
+
|
49 |
+
def isatty(self):
|
50 |
+
stream = self.__wrapped
|
51 |
+
if 'PYCHARM_HOSTED' in os.environ:
|
52 |
+
if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
|
53 |
+
return True
|
54 |
+
try:
|
55 |
+
stream_isatty = stream.isatty
|
56 |
+
except AttributeError:
|
57 |
+
return False
|
58 |
+
else:
|
59 |
+
return stream_isatty()
|
60 |
+
|
61 |
+
@property
|
62 |
+
def closed(self):
|
63 |
+
stream = self.__wrapped
|
64 |
+
try:
|
65 |
+
return stream.closed
|
66 |
+
# AttributeError in the case that the stream doesn't support being closed
|
67 |
+
# ValueError for the case that the stream has already been detached when atexit runs
|
68 |
+
except (AttributeError, ValueError):
|
69 |
+
return True
|
70 |
+
|
71 |
+
|
72 |
+
class AnsiToWin32(object):
|
73 |
+
'''
|
74 |
+
Implements a 'write()' method which, on Windows, will strip ANSI character
|
75 |
+
sequences from the text, and if outputting to a tty, will convert them into
|
76 |
+
win32 function calls.
|
77 |
+
'''
|
78 |
+
ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
|
79 |
+
ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command
|
80 |
+
|
81 |
+
def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
|
82 |
+
# The wrapped stream (normally sys.stdout or sys.stderr)
|
83 |
+
self.wrapped = wrapped
|
84 |
+
|
85 |
+
# should we reset colors to defaults after every .write()
|
86 |
+
self.autoreset = autoreset
|
87 |
+
|
88 |
+
# create the proxy wrapping our output stream
|
89 |
+
self.stream = StreamWrapper(wrapped, self)
|
90 |
+
|
91 |
+
on_windows = os.name == 'nt'
|
92 |
+
# We test if the WinAPI works, because even if we are on Windows
|
93 |
+
# we may be using a terminal that doesn't support the WinAPI
|
94 |
+
# (e.g. Cygwin Terminal). In this case it's up to the terminal
|
95 |
+
# to support the ANSI codes.
|
96 |
+
conversion_supported = on_windows and winapi_test()
|
97 |
+
try:
|
98 |
+
fd = wrapped.fileno()
|
99 |
+
except Exception:
|
100 |
+
fd = -1
|
101 |
+
system_has_native_ansi = not on_windows or enable_vt_processing(fd)
|
102 |
+
have_tty = not self.stream.closed and self.stream.isatty()
|
103 |
+
need_conversion = conversion_supported and not system_has_native_ansi
|
104 |
+
|
105 |
+
# should we strip ANSI sequences from our output?
|
106 |
+
if strip is None:
|
107 |
+
strip = need_conversion or not have_tty
|
108 |
+
self.strip = strip
|
109 |
+
|
110 |
+
# should we should convert ANSI sequences into win32 calls?
|
111 |
+
if convert is None:
|
112 |
+
convert = need_conversion and have_tty
|
113 |
+
self.convert = convert
|
114 |
+
|
115 |
+
# dict of ansi codes to win32 functions and parameters
|
116 |
+
self.win32_calls = self.get_win32_calls()
|
117 |
+
|
118 |
+
# are we wrapping stderr?
|
119 |
+
self.on_stderr = self.wrapped is sys.stderr
|
120 |
+
|
121 |
+
def should_wrap(self):
|
122 |
+
'''
|
123 |
+
True if this class is actually needed. If false, then the output
|
124 |
+
stream will not be affected, nor will win32 calls be issued, so
|
125 |
+
wrapping stdout is not actually required. This will generally be
|
126 |
+
False on non-Windows platforms, unless optional functionality like
|
127 |
+
autoreset has been requested using kwargs to init()
|
128 |
+
'''
|
129 |
+
return self.convert or self.strip or self.autoreset
|
130 |
+
|
131 |
+
def get_win32_calls(self):
|
132 |
+
if self.convert and winterm:
|
133 |
+
return {
|
134 |
+
AnsiStyle.RESET_ALL: (winterm.reset_all, ),
|
135 |
+
AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
|
136 |
+
AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
|
137 |
+
AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
|
138 |
+
AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
|
139 |
+
AnsiFore.RED: (winterm.fore, WinColor.RED),
|
140 |
+
AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
|
141 |
+
AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
|
142 |
+
AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
|
143 |
+
AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
|
144 |
+
AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
|
145 |
+
AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
|
146 |
+
AnsiFore.RESET: (winterm.fore, ),
|
147 |
+
AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),
|
148 |
+
AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),
|
149 |
+
AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),
|
150 |
+
AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),
|
151 |
+
AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),
|
152 |
+
AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),
|
153 |
+
AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),
|
154 |
+
AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),
|
155 |
+
AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
|
156 |
+
AnsiBack.RED: (winterm.back, WinColor.RED),
|
157 |
+
AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
|
158 |
+
AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
|
159 |
+
AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
|
160 |
+
AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
|
161 |
+
AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
|
162 |
+
AnsiBack.WHITE: (winterm.back, WinColor.GREY),
|
163 |
+
AnsiBack.RESET: (winterm.back, ),
|
164 |
+
AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),
|
165 |
+
AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),
|
166 |
+
AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),
|
167 |
+
AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),
|
168 |
+
AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),
|
169 |
+
AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),
|
170 |
+
AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),
|
171 |
+
AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),
|
172 |
+
}
|
173 |
+
return dict()
|
174 |
+
|
175 |
+
def write(self, text):
|
176 |
+
if self.strip or self.convert:
|
177 |
+
self.write_and_convert(text)
|
178 |
+
else:
|
179 |
+
self.wrapped.write(text)
|
180 |
+
self.wrapped.flush()
|
181 |
+
if self.autoreset:
|
182 |
+
self.reset_all()
|
183 |
+
|
184 |
+
|
185 |
+
def reset_all(self):
|
186 |
+
if self.convert:
|
187 |
+
self.call_win32('m', (0,))
|
188 |
+
elif not self.strip and not self.stream.closed:
|
189 |
+
self.wrapped.write(Style.RESET_ALL)
|
190 |
+
|
191 |
+
|
192 |
+
def write_and_convert(self, text):
|
193 |
+
'''
|
194 |
+
Write the given text to our wrapped stream, stripping any ANSI
|
195 |
+
sequences from the text, and optionally converting them into win32
|
196 |
+
calls.
|
197 |
+
'''
|
198 |
+
cursor = 0
|
199 |
+
text = self.convert_osc(text)
|
200 |
+
for match in self.ANSI_CSI_RE.finditer(text):
|
201 |
+
start, end = match.span()
|
202 |
+
self.write_plain_text(text, cursor, start)
|
203 |
+
self.convert_ansi(*match.groups())
|
204 |
+
cursor = end
|
205 |
+
self.write_plain_text(text, cursor, len(text))
|
206 |
+
|
207 |
+
|
208 |
+
def write_plain_text(self, text, start, end):
|
209 |
+
if start < end:
|
210 |
+
self.wrapped.write(text[start:end])
|
211 |
+
self.wrapped.flush()
|
212 |
+
|
213 |
+
|
214 |
+
def convert_ansi(self, paramstring, command):
|
215 |
+
if self.convert:
|
216 |
+
params = self.extract_params(command, paramstring)
|
217 |
+
self.call_win32(command, params)
|
218 |
+
|
219 |
+
|
220 |
+
def extract_params(self, command, paramstring):
|
221 |
+
if command in 'Hf':
|
222 |
+
params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))
|
223 |
+
while len(params) < 2:
|
224 |
+
# defaults:
|
225 |
+
params = params + (1,)
|
226 |
+
else:
|
227 |
+
params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
|
228 |
+
if len(params) == 0:
|
229 |
+
# defaults:
|
230 |
+
if command in 'JKm':
|
231 |
+
params = (0,)
|
232 |
+
elif command in 'ABCD':
|
233 |
+
params = (1,)
|
234 |
+
|
235 |
+
return params
|
236 |
+
|
237 |
+
|
238 |
+
def call_win32(self, command, params):
|
239 |
+
if command == 'm':
|
240 |
+
for param in params:
|
241 |
+
if param in self.win32_calls:
|
242 |
+
func_args = self.win32_calls[param]
|
243 |
+
func = func_args[0]
|
244 |
+
args = func_args[1:]
|
245 |
+
kwargs = dict(on_stderr=self.on_stderr)
|
246 |
+
func(*args, **kwargs)
|
247 |
+
elif command in 'J':
|
248 |
+
winterm.erase_screen(params[0], on_stderr=self.on_stderr)
|
249 |
+
elif command in 'K':
|
250 |
+
winterm.erase_line(params[0], on_stderr=self.on_stderr)
|
251 |
+
elif command in 'Hf': # cursor position - absolute
|
252 |
+
winterm.set_cursor_position(params, on_stderr=self.on_stderr)
|
253 |
+
elif command in 'ABCD': # cursor position - relative
|
254 |
+
n = params[0]
|
255 |
+
# A - up, B - down, C - forward, D - back
|
256 |
+
x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]
|
257 |
+
winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)
|
258 |
+
|
259 |
+
|
260 |
+
def convert_osc(self, text):
|
261 |
+
for match in self.ANSI_OSC_RE.finditer(text):
|
262 |
+
start, end = match.span()
|
263 |
+
text = text[:start] + text[end:]
|
264 |
+
paramstring, command = match.groups()
|
265 |
+
if command == BEL:
|
266 |
+
if paramstring.count(";") == 1:
|
267 |
+
params = paramstring.split(";")
|
268 |
+
# 0 - change title and icon (we will only change title)
|
269 |
+
# 1 - change icon (we don't support this)
|
270 |
+
# 2 - change title
|
271 |
+
if params[0] in '02':
|
272 |
+
winterm.set_title(params[1])
|
273 |
+
return text
|
274 |
+
|
275 |
+
|
276 |
+
def flush(self):
|
277 |
+
self.wrapped.flush()
|
lib/python3.10/site-packages/colorama/initialise.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import atexit
|
3 |
+
import contextlib
|
4 |
+
import sys
|
5 |
+
|
6 |
+
from .ansitowin32 import AnsiToWin32
|
7 |
+
|
8 |
+
|
9 |
+
def _wipe_internal_state_for_tests():
|
10 |
+
global orig_stdout, orig_stderr
|
11 |
+
orig_stdout = None
|
12 |
+
orig_stderr = None
|
13 |
+
|
14 |
+
global wrapped_stdout, wrapped_stderr
|
15 |
+
wrapped_stdout = None
|
16 |
+
wrapped_stderr = None
|
17 |
+
|
18 |
+
global atexit_done
|
19 |
+
atexit_done = False
|
20 |
+
|
21 |
+
global fixed_windows_console
|
22 |
+
fixed_windows_console = False
|
23 |
+
|
24 |
+
try:
|
25 |
+
# no-op if it wasn't registered
|
26 |
+
atexit.unregister(reset_all)
|
27 |
+
except AttributeError:
|
28 |
+
# python 2: no atexit.unregister. Oh well, we did our best.
|
29 |
+
pass
|
30 |
+
|
31 |
+
|
32 |
+
def reset_all():
|
33 |
+
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
|
34 |
+
AnsiToWin32(orig_stdout).reset_all()
|
35 |
+
|
36 |
+
|
37 |
+
def init(autoreset=False, convert=None, strip=None, wrap=True):
|
38 |
+
|
39 |
+
if not wrap and any([autoreset, convert, strip]):
|
40 |
+
raise ValueError('wrap=False conflicts with any other arg=True')
|
41 |
+
|
42 |
+
global wrapped_stdout, wrapped_stderr
|
43 |
+
global orig_stdout, orig_stderr
|
44 |
+
|
45 |
+
orig_stdout = sys.stdout
|
46 |
+
orig_stderr = sys.stderr
|
47 |
+
|
48 |
+
if sys.stdout is None:
|
49 |
+
wrapped_stdout = None
|
50 |
+
else:
|
51 |
+
sys.stdout = wrapped_stdout = \
|
52 |
+
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
|
53 |
+
if sys.stderr is None:
|
54 |
+
wrapped_stderr = None
|
55 |
+
else:
|
56 |
+
sys.stderr = wrapped_stderr = \
|
57 |
+
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
|
58 |
+
|
59 |
+
global atexit_done
|
60 |
+
if not atexit_done:
|
61 |
+
atexit.register(reset_all)
|
62 |
+
atexit_done = True
|
63 |
+
|
64 |
+
|
65 |
+
def deinit():
|
66 |
+
if orig_stdout is not None:
|
67 |
+
sys.stdout = orig_stdout
|
68 |
+
if orig_stderr is not None:
|
69 |
+
sys.stderr = orig_stderr
|
70 |
+
|
71 |
+
|
72 |
+
def just_fix_windows_console():
|
73 |
+
global fixed_windows_console
|
74 |
+
|
75 |
+
if sys.platform != "win32":
|
76 |
+
return
|
77 |
+
if fixed_windows_console:
|
78 |
+
return
|
79 |
+
if wrapped_stdout is not None or wrapped_stderr is not None:
|
80 |
+
# Someone already ran init() and it did stuff, so we won't second-guess them
|
81 |
+
return
|
82 |
+
|
83 |
+
# On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the
|
84 |
+
# native ANSI support in the console as a side-effect. We only need to actually
|
85 |
+
# replace sys.stdout/stderr if we're in the old-style conversion mode.
|
86 |
+
new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False)
|
87 |
+
if new_stdout.convert:
|
88 |
+
sys.stdout = new_stdout
|
89 |
+
new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False)
|
90 |
+
if new_stderr.convert:
|
91 |
+
sys.stderr = new_stderr
|
92 |
+
|
93 |
+
fixed_windows_console = True
|
94 |
+
|
95 |
+
@contextlib.contextmanager
|
96 |
+
def colorama_text(*args, **kwargs):
|
97 |
+
init(*args, **kwargs)
|
98 |
+
try:
|
99 |
+
yield
|
100 |
+
finally:
|
101 |
+
deinit()
|
102 |
+
|
103 |
+
|
104 |
+
def reinit():
|
105 |
+
if wrapped_stdout is not None:
|
106 |
+
sys.stdout = wrapped_stdout
|
107 |
+
if wrapped_stderr is not None:
|
108 |
+
sys.stderr = wrapped_stderr
|
109 |
+
|
110 |
+
|
111 |
+
def wrap_stream(stream, convert, strip, autoreset, wrap):
|
112 |
+
if wrap:
|
113 |
+
wrapper = AnsiToWin32(stream,
|
114 |
+
convert=convert, strip=strip, autoreset=autoreset)
|
115 |
+
if wrapper.should_wrap():
|
116 |
+
stream = wrapper.stream
|
117 |
+
return stream
|
118 |
+
|
119 |
+
|
120 |
+
# Use this for initial setup as well, to reduce code duplication
|
121 |
+
_wipe_internal_state_for_tests()
|
lib/python3.10/site-packages/colorama/win32.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
|
3 |
+
# from winbase.h
|
4 |
+
STDOUT = -11
|
5 |
+
STDERR = -12
|
6 |
+
|
7 |
+
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
|
8 |
+
|
9 |
+
try:
|
10 |
+
import ctypes
|
11 |
+
from ctypes import LibraryLoader
|
12 |
+
windll = LibraryLoader(ctypes.WinDLL)
|
13 |
+
from ctypes import wintypes
|
14 |
+
except (AttributeError, ImportError):
|
15 |
+
windll = None
|
16 |
+
SetConsoleTextAttribute = lambda *_: None
|
17 |
+
winapi_test = lambda *_: None
|
18 |
+
else:
|
19 |
+
from ctypes import byref, Structure, c_char, POINTER
|
20 |
+
|
21 |
+
COORD = wintypes._COORD
|
22 |
+
|
23 |
+
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
|
24 |
+
"""struct in wincon.h."""
|
25 |
+
_fields_ = [
|
26 |
+
("dwSize", COORD),
|
27 |
+
("dwCursorPosition", COORD),
|
28 |
+
("wAttributes", wintypes.WORD),
|
29 |
+
("srWindow", wintypes.SMALL_RECT),
|
30 |
+
("dwMaximumWindowSize", COORD),
|
31 |
+
]
|
32 |
+
def __str__(self):
|
33 |
+
return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
|
34 |
+
self.dwSize.Y, self.dwSize.X
|
35 |
+
, self.dwCursorPosition.Y, self.dwCursorPosition.X
|
36 |
+
, self.wAttributes
|
37 |
+
, self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
|
38 |
+
, self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
|
39 |
+
)
|
40 |
+
|
41 |
+
_GetStdHandle = windll.kernel32.GetStdHandle
|
42 |
+
_GetStdHandle.argtypes = [
|
43 |
+
wintypes.DWORD,
|
44 |
+
]
|
45 |
+
_GetStdHandle.restype = wintypes.HANDLE
|
46 |
+
|
47 |
+
_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
|
48 |
+
_GetConsoleScreenBufferInfo.argtypes = [
|
49 |
+
wintypes.HANDLE,
|
50 |
+
POINTER(CONSOLE_SCREEN_BUFFER_INFO),
|
51 |
+
]
|
52 |
+
_GetConsoleScreenBufferInfo.restype = wintypes.BOOL
|
53 |
+
|
54 |
+
_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
|
55 |
+
_SetConsoleTextAttribute.argtypes = [
|
56 |
+
wintypes.HANDLE,
|
57 |
+
wintypes.WORD,
|
58 |
+
]
|
59 |
+
_SetConsoleTextAttribute.restype = wintypes.BOOL
|
60 |
+
|
61 |
+
_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
|
62 |
+
_SetConsoleCursorPosition.argtypes = [
|
63 |
+
wintypes.HANDLE,
|
64 |
+
COORD,
|
65 |
+
]
|
66 |
+
_SetConsoleCursorPosition.restype = wintypes.BOOL
|
67 |
+
|
68 |
+
_FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
|
69 |
+
_FillConsoleOutputCharacterA.argtypes = [
|
70 |
+
wintypes.HANDLE,
|
71 |
+
c_char,
|
72 |
+
wintypes.DWORD,
|
73 |
+
COORD,
|
74 |
+
POINTER(wintypes.DWORD),
|
75 |
+
]
|
76 |
+
_FillConsoleOutputCharacterA.restype = wintypes.BOOL
|
77 |
+
|
78 |
+
_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
|
79 |
+
_FillConsoleOutputAttribute.argtypes = [
|
80 |
+
wintypes.HANDLE,
|
81 |
+
wintypes.WORD,
|
82 |
+
wintypes.DWORD,
|
83 |
+
COORD,
|
84 |
+
POINTER(wintypes.DWORD),
|
85 |
+
]
|
86 |
+
_FillConsoleOutputAttribute.restype = wintypes.BOOL
|
87 |
+
|
88 |
+
_SetConsoleTitleW = windll.kernel32.SetConsoleTitleW
|
89 |
+
_SetConsoleTitleW.argtypes = [
|
90 |
+
wintypes.LPCWSTR
|
91 |
+
]
|
92 |
+
_SetConsoleTitleW.restype = wintypes.BOOL
|
93 |
+
|
94 |
+
_GetConsoleMode = windll.kernel32.GetConsoleMode
|
95 |
+
_GetConsoleMode.argtypes = [
|
96 |
+
wintypes.HANDLE,
|
97 |
+
POINTER(wintypes.DWORD)
|
98 |
+
]
|
99 |
+
_GetConsoleMode.restype = wintypes.BOOL
|
100 |
+
|
101 |
+
_SetConsoleMode = windll.kernel32.SetConsoleMode
|
102 |
+
_SetConsoleMode.argtypes = [
|
103 |
+
wintypes.HANDLE,
|
104 |
+
wintypes.DWORD
|
105 |
+
]
|
106 |
+
_SetConsoleMode.restype = wintypes.BOOL
|
107 |
+
|
108 |
+
def _winapi_test(handle):
|
109 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
110 |
+
success = _GetConsoleScreenBufferInfo(
|
111 |
+
handle, byref(csbi))
|
112 |
+
return bool(success)
|
113 |
+
|
114 |
+
def winapi_test():
|
115 |
+
return any(_winapi_test(h) for h in
|
116 |
+
(_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))
|
117 |
+
|
118 |
+
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
|
119 |
+
handle = _GetStdHandle(stream_id)
|
120 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
121 |
+
success = _GetConsoleScreenBufferInfo(
|
122 |
+
handle, byref(csbi))
|
123 |
+
return csbi
|
124 |
+
|
125 |
+
def SetConsoleTextAttribute(stream_id, attrs):
|
126 |
+
handle = _GetStdHandle(stream_id)
|
127 |
+
return _SetConsoleTextAttribute(handle, attrs)
|
128 |
+
|
129 |
+
def SetConsoleCursorPosition(stream_id, position, adjust=True):
|
130 |
+
position = COORD(*position)
|
131 |
+
# If the position is out of range, do nothing.
|
132 |
+
if position.Y <= 0 or position.X <= 0:
|
133 |
+
return
|
134 |
+
# Adjust for Windows' SetConsoleCursorPosition:
|
135 |
+
# 1. being 0-based, while ANSI is 1-based.
|
136 |
+
# 2. expecting (x,y), while ANSI uses (y,x).
|
137 |
+
adjusted_position = COORD(position.Y - 1, position.X - 1)
|
138 |
+
if adjust:
|
139 |
+
# Adjust for viewport's scroll position
|
140 |
+
sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
|
141 |
+
adjusted_position.Y += sr.Top
|
142 |
+
adjusted_position.X += sr.Left
|
143 |
+
# Resume normal processing
|
144 |
+
handle = _GetStdHandle(stream_id)
|
145 |
+
return _SetConsoleCursorPosition(handle, adjusted_position)
|
146 |
+
|
147 |
+
def FillConsoleOutputCharacter(stream_id, char, length, start):
|
148 |
+
handle = _GetStdHandle(stream_id)
|
149 |
+
char = c_char(char.encode())
|
150 |
+
length = wintypes.DWORD(length)
|
151 |
+
num_written = wintypes.DWORD(0)
|
152 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
153 |
+
success = _FillConsoleOutputCharacterA(
|
154 |
+
handle, char, length, start, byref(num_written))
|
155 |
+
return num_written.value
|
156 |
+
|
157 |
+
def FillConsoleOutputAttribute(stream_id, attr, length, start):
|
158 |
+
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
|
159 |
+
handle = _GetStdHandle(stream_id)
|
160 |
+
attribute = wintypes.WORD(attr)
|
161 |
+
length = wintypes.DWORD(length)
|
162 |
+
num_written = wintypes.DWORD(0)
|
163 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
164 |
+
return _FillConsoleOutputAttribute(
|
165 |
+
handle, attribute, length, start, byref(num_written))
|
166 |
+
|
167 |
+
def SetConsoleTitle(title):
|
168 |
+
return _SetConsoleTitleW(title)
|
169 |
+
|
170 |
+
def GetConsoleMode(handle):
|
171 |
+
mode = wintypes.DWORD()
|
172 |
+
success = _GetConsoleMode(handle, byref(mode))
|
173 |
+
if not success:
|
174 |
+
raise ctypes.WinError()
|
175 |
+
return mode.value
|
176 |
+
|
177 |
+
def SetConsoleMode(handle, mode):
|
178 |
+
success = _SetConsoleMode(handle, mode)
|
179 |
+
if not success:
|
180 |
+
raise ctypes.WinError()
|
lib/python3.10/site-packages/colorama/winterm.py
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
try:
|
3 |
+
from msvcrt import get_osfhandle
|
4 |
+
except ImportError:
|
5 |
+
def get_osfhandle(_):
|
6 |
+
raise OSError("This isn't windows!")
|
7 |
+
|
8 |
+
|
9 |
+
from . import win32
|
10 |
+
|
11 |
+
# from wincon.h
|
12 |
+
class WinColor(object):
|
13 |
+
BLACK = 0
|
14 |
+
BLUE = 1
|
15 |
+
GREEN = 2
|
16 |
+
CYAN = 3
|
17 |
+
RED = 4
|
18 |
+
MAGENTA = 5
|
19 |
+
YELLOW = 6
|
20 |
+
GREY = 7
|
21 |
+
|
22 |
+
# from wincon.h
|
23 |
+
class WinStyle(object):
|
24 |
+
NORMAL = 0x00 # dim text, dim background
|
25 |
+
BRIGHT = 0x08 # bright text, dim background
|
26 |
+
BRIGHT_BACKGROUND = 0x80 # dim text, bright background
|
27 |
+
|
28 |
+
class WinTerm(object):
|
29 |
+
|
30 |
+
def __init__(self):
|
31 |
+
self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
|
32 |
+
self.set_attrs(self._default)
|
33 |
+
self._default_fore = self._fore
|
34 |
+
self._default_back = self._back
|
35 |
+
self._default_style = self._style
|
36 |
+
# In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.
|
37 |
+
# So that LIGHT_EX colors and BRIGHT style do not clobber each other,
|
38 |
+
# we track them separately, since LIGHT_EX is overwritten by Fore/Back
|
39 |
+
# and BRIGHT is overwritten by Style codes.
|
40 |
+
self._light = 0
|
41 |
+
|
42 |
+
def get_attrs(self):
|
43 |
+
return self._fore + self._back * 16 + (self._style | self._light)
|
44 |
+
|
45 |
+
def set_attrs(self, value):
|
46 |
+
self._fore = value & 7
|
47 |
+
self._back = (value >> 4) & 7
|
48 |
+
self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)
|
49 |
+
|
50 |
+
def reset_all(self, on_stderr=None):
|
51 |
+
self.set_attrs(self._default)
|
52 |
+
self.set_console(attrs=self._default)
|
53 |
+
self._light = 0
|
54 |
+
|
55 |
+
def fore(self, fore=None, light=False, on_stderr=False):
|
56 |
+
if fore is None:
|
57 |
+
fore = self._default_fore
|
58 |
+
self._fore = fore
|
59 |
+
# Emulate LIGHT_EX with BRIGHT Style
|
60 |
+
if light:
|
61 |
+
self._light |= WinStyle.BRIGHT
|
62 |
+
else:
|
63 |
+
self._light &= ~WinStyle.BRIGHT
|
64 |
+
self.set_console(on_stderr=on_stderr)
|
65 |
+
|
66 |
+
def back(self, back=None, light=False, on_stderr=False):
|
67 |
+
if back is None:
|
68 |
+
back = self._default_back
|
69 |
+
self._back = back
|
70 |
+
# Emulate LIGHT_EX with BRIGHT_BACKGROUND Style
|
71 |
+
if light:
|
72 |
+
self._light |= WinStyle.BRIGHT_BACKGROUND
|
73 |
+
else:
|
74 |
+
self._light &= ~WinStyle.BRIGHT_BACKGROUND
|
75 |
+
self.set_console(on_stderr=on_stderr)
|
76 |
+
|
77 |
+
def style(self, style=None, on_stderr=False):
|
78 |
+
if style is None:
|
79 |
+
style = self._default_style
|
80 |
+
self._style = style
|
81 |
+
self.set_console(on_stderr=on_stderr)
|
82 |
+
|
83 |
+
def set_console(self, attrs=None, on_stderr=False):
|
84 |
+
if attrs is None:
|
85 |
+
attrs = self.get_attrs()
|
86 |
+
handle = win32.STDOUT
|
87 |
+
if on_stderr:
|
88 |
+
handle = win32.STDERR
|
89 |
+
win32.SetConsoleTextAttribute(handle, attrs)
|
90 |
+
|
91 |
+
def get_position(self, handle):
|
92 |
+
position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
|
93 |
+
# Because Windows coordinates are 0-based,
|
94 |
+
# and win32.SetConsoleCursorPosition expects 1-based.
|
95 |
+
position.X += 1
|
96 |
+
position.Y += 1
|
97 |
+
return position
|
98 |
+
|
99 |
+
def set_cursor_position(self, position=None, on_stderr=False):
|
100 |
+
if position is None:
|
101 |
+
# I'm not currently tracking the position, so there is no default.
|
102 |
+
# position = self.get_position()
|
103 |
+
return
|
104 |
+
handle = win32.STDOUT
|
105 |
+
if on_stderr:
|
106 |
+
handle = win32.STDERR
|
107 |
+
win32.SetConsoleCursorPosition(handle, position)
|
108 |
+
|
109 |
+
def cursor_adjust(self, x, y, on_stderr=False):
|
110 |
+
handle = win32.STDOUT
|
111 |
+
if on_stderr:
|
112 |
+
handle = win32.STDERR
|
113 |
+
position = self.get_position(handle)
|
114 |
+
adjusted_position = (position.Y + y, position.X + x)
|
115 |
+
win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)
|
116 |
+
|
117 |
+
def erase_screen(self, mode=0, on_stderr=False):
|
118 |
+
# 0 should clear from the cursor to the end of the screen.
|
119 |
+
# 1 should clear from the cursor to the beginning of the screen.
|
120 |
+
# 2 should clear the entire screen, and move cursor to (1,1)
|
121 |
+
handle = win32.STDOUT
|
122 |
+
if on_stderr:
|
123 |
+
handle = win32.STDERR
|
124 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
125 |
+
# get the number of character cells in the current buffer
|
126 |
+
cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y
|
127 |
+
# get number of character cells before current cursor position
|
128 |
+
cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X
|
129 |
+
if mode == 0:
|
130 |
+
from_coord = csbi.dwCursorPosition
|
131 |
+
cells_to_erase = cells_in_screen - cells_before_cursor
|
132 |
+
elif mode == 1:
|
133 |
+
from_coord = win32.COORD(0, 0)
|
134 |
+
cells_to_erase = cells_before_cursor
|
135 |
+
elif mode == 2:
|
136 |
+
from_coord = win32.COORD(0, 0)
|
137 |
+
cells_to_erase = cells_in_screen
|
138 |
+
else:
|
139 |
+
# invalid mode
|
140 |
+
return
|
141 |
+
# fill the entire screen with blanks
|
142 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
143 |
+
# now set the buffer's attributes accordingly
|
144 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
145 |
+
if mode == 2:
|
146 |
+
# put the cursor where needed
|
147 |
+
win32.SetConsoleCursorPosition(handle, (1, 1))
|
148 |
+
|
149 |
+
def erase_line(self, mode=0, on_stderr=False):
|
150 |
+
# 0 should clear from the cursor to the end of the line.
|
151 |
+
# 1 should clear from the cursor to the beginning of the line.
|
152 |
+
# 2 should clear the entire line.
|
153 |
+
handle = win32.STDOUT
|
154 |
+
if on_stderr:
|
155 |
+
handle = win32.STDERR
|
156 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
157 |
+
if mode == 0:
|
158 |
+
from_coord = csbi.dwCursorPosition
|
159 |
+
cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X
|
160 |
+
elif mode == 1:
|
161 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
162 |
+
cells_to_erase = csbi.dwCursorPosition.X
|
163 |
+
elif mode == 2:
|
164 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
165 |
+
cells_to_erase = csbi.dwSize.X
|
166 |
+
else:
|
167 |
+
# invalid mode
|
168 |
+
return
|
169 |
+
# fill the entire screen with blanks
|
170 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
171 |
+
# now set the buffer's attributes accordingly
|
172 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
173 |
+
|
174 |
+
def set_title(self, title):
|
175 |
+
win32.SetConsoleTitle(title)
|
176 |
+
|
177 |
+
|
178 |
+
def enable_vt_processing(fd):
|
179 |
+
if win32.windll is None or not win32.winapi_test():
|
180 |
+
return False
|
181 |
+
|
182 |
+
try:
|
183 |
+
handle = get_osfhandle(fd)
|
184 |
+
mode = win32.GetConsoleMode(handle)
|
185 |
+
win32.SetConsoleMode(
|
186 |
+
handle,
|
187 |
+
mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING,
|
188 |
+
)
|
189 |
+
|
190 |
+
mode = win32.GetConsoleMode(handle)
|
191 |
+
if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING:
|
192 |
+
return True
|
193 |
+
# Can get TypeError in testsuite where 'fd' is a Mock()
|
194 |
+
except (OSError, TypeError):
|
195 |
+
return False
|
lib/python3.10/site-packages/cryptography/hazmat/backends/__init__.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from __future__ import annotations
|
6 |
+
|
7 |
+
from typing import Any
|
8 |
+
|
9 |
+
|
10 |
+
def default_backend() -> Any:
|
11 |
+
from cryptography.hazmat.backends.openssl.backend import backend
|
12 |
+
|
13 |
+
return backend
|
lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from __future__ import annotations
|
6 |
+
|
7 |
+
from cryptography.hazmat.backends.openssl.backend import backend
|
8 |
+
|
9 |
+
__all__ = ["backend"]
|
lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/backend.py
ADDED
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from __future__ import annotations
|
6 |
+
|
7 |
+
from cryptography.hazmat.bindings._rust import openssl as rust_openssl
|
8 |
+
from cryptography.hazmat.bindings.openssl import binding
|
9 |
+
from cryptography.hazmat.primitives import hashes
|
10 |
+
from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding
|
11 |
+
from cryptography.hazmat.primitives.asymmetric import ec
|
12 |
+
from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
|
13 |
+
from cryptography.hazmat.primitives.asymmetric.padding import (
|
14 |
+
MGF1,
|
15 |
+
OAEP,
|
16 |
+
PSS,
|
17 |
+
PKCS1v15,
|
18 |
+
)
|
19 |
+
from cryptography.hazmat.primitives.ciphers import (
|
20 |
+
CipherAlgorithm,
|
21 |
+
)
|
22 |
+
from cryptography.hazmat.primitives.ciphers.algorithms import (
|
23 |
+
AES,
|
24 |
+
)
|
25 |
+
from cryptography.hazmat.primitives.ciphers.modes import (
|
26 |
+
CBC,
|
27 |
+
Mode,
|
28 |
+
)
|
29 |
+
|
30 |
+
|
31 |
+
class Backend:
|
32 |
+
"""
|
33 |
+
OpenSSL API binding interfaces.
|
34 |
+
"""
|
35 |
+
|
36 |
+
name = "openssl"
|
37 |
+
|
38 |
+
# TripleDES encryption is disallowed/deprecated throughout 2023 in
|
39 |
+
# FIPS 140-3. To keep it simple we denylist any use of TripleDES (TDEA).
|
40 |
+
_fips_ciphers = (AES,)
|
41 |
+
# Sometimes SHA1 is still permissible. That logic is contained
|
42 |
+
# within the various *_supported methods.
|
43 |
+
_fips_hashes = (
|
44 |
+
hashes.SHA224,
|
45 |
+
hashes.SHA256,
|
46 |
+
hashes.SHA384,
|
47 |
+
hashes.SHA512,
|
48 |
+
hashes.SHA512_224,
|
49 |
+
hashes.SHA512_256,
|
50 |
+
hashes.SHA3_224,
|
51 |
+
hashes.SHA3_256,
|
52 |
+
hashes.SHA3_384,
|
53 |
+
hashes.SHA3_512,
|
54 |
+
hashes.SHAKE128,
|
55 |
+
hashes.SHAKE256,
|
56 |
+
)
|
57 |
+
_fips_ecdh_curves = (
|
58 |
+
ec.SECP224R1,
|
59 |
+
ec.SECP256R1,
|
60 |
+
ec.SECP384R1,
|
61 |
+
ec.SECP521R1,
|
62 |
+
)
|
63 |
+
_fips_rsa_min_key_size = 2048
|
64 |
+
_fips_rsa_min_public_exponent = 65537
|
65 |
+
_fips_dsa_min_modulus = 1 << 2048
|
66 |
+
_fips_dh_min_key_size = 2048
|
67 |
+
_fips_dh_min_modulus = 1 << _fips_dh_min_key_size
|
68 |
+
|
69 |
+
def __init__(self) -> None:
|
70 |
+
self._binding = binding.Binding()
|
71 |
+
self._ffi = self._binding.ffi
|
72 |
+
self._lib = self._binding.lib
|
73 |
+
self._fips_enabled = rust_openssl.is_fips_enabled()
|
74 |
+
|
75 |
+
def __repr__(self) -> str:
|
76 |
+
return (
|
77 |
+
f"<OpenSSLBackend(version: {self.openssl_version_text()}, "
|
78 |
+
f"FIPS: {self._fips_enabled}, "
|
79 |
+
f"Legacy: {rust_openssl._legacy_provider_loaded})>"
|
80 |
+
)
|
81 |
+
|
82 |
+
def openssl_assert(self, ok: bool) -> None:
|
83 |
+
return binding._openssl_assert(ok)
|
84 |
+
|
85 |
+
def _enable_fips(self) -> None:
|
86 |
+
# This function enables FIPS mode for OpenSSL 3.0.0 on installs that
|
87 |
+
# have the FIPS provider installed properly.
|
88 |
+
rust_openssl.enable_fips(rust_openssl._providers)
|
89 |
+
assert rust_openssl.is_fips_enabled()
|
90 |
+
self._fips_enabled = rust_openssl.is_fips_enabled()
|
91 |
+
|
92 |
+
def openssl_version_text(self) -> str:
|
93 |
+
"""
|
94 |
+
Friendly string name of the loaded OpenSSL library. This is not
|
95 |
+
necessarily the same version as it was compiled against.
|
96 |
+
|
97 |
+
Example: OpenSSL 3.2.1 30 Jan 2024
|
98 |
+
"""
|
99 |
+
return rust_openssl.openssl_version_text()
|
100 |
+
|
101 |
+
def openssl_version_number(self) -> int:
|
102 |
+
return rust_openssl.openssl_version()
|
103 |
+
|
104 |
+
def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
|
105 |
+
if self._fips_enabled and not isinstance(algorithm, self._fips_hashes):
|
106 |
+
return False
|
107 |
+
|
108 |
+
return rust_openssl.hashes.hash_supported(algorithm)
|
109 |
+
|
110 |
+
def signature_hash_supported(
|
111 |
+
self, algorithm: hashes.HashAlgorithm
|
112 |
+
) -> bool:
|
113 |
+
# Dedicated check for hashing algorithm use in message digest for
|
114 |
+
# signatures, e.g. RSA PKCS#1 v1.5 SHA1 (sha1WithRSAEncryption).
|
115 |
+
if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
|
116 |
+
return False
|
117 |
+
return self.hash_supported(algorithm)
|
118 |
+
|
119 |
+
def scrypt_supported(self) -> bool:
|
120 |
+
if self._fips_enabled:
|
121 |
+
return False
|
122 |
+
else:
|
123 |
+
return hasattr(rust_openssl.kdf.Scrypt, "derive")
|
124 |
+
|
125 |
+
def argon2_supported(self) -> bool:
|
126 |
+
if self._fips_enabled:
|
127 |
+
return False
|
128 |
+
else:
|
129 |
+
return hasattr(rust_openssl.kdf.Argon2id, "derive")
|
130 |
+
|
131 |
+
def hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
|
132 |
+
# FIPS mode still allows SHA1 for HMAC
|
133 |
+
if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
|
134 |
+
return True
|
135 |
+
|
136 |
+
return self.hash_supported(algorithm)
|
137 |
+
|
138 |
+
def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool:
|
139 |
+
if self._fips_enabled:
|
140 |
+
# FIPS mode requires AES. TripleDES is disallowed/deprecated in
|
141 |
+
# FIPS 140-3.
|
142 |
+
if not isinstance(cipher, self._fips_ciphers):
|
143 |
+
return False
|
144 |
+
|
145 |
+
return rust_openssl.ciphers.cipher_supported(cipher, mode)
|
146 |
+
|
147 |
+
def pbkdf2_hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
|
148 |
+
return self.hmac_supported(algorithm)
|
149 |
+
|
150 |
+
def _consume_errors(self) -> list[rust_openssl.OpenSSLError]:
|
151 |
+
return rust_openssl.capture_error_stack()
|
152 |
+
|
153 |
+
def _oaep_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
|
154 |
+
if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
|
155 |
+
return False
|
156 |
+
|
157 |
+
return isinstance(
|
158 |
+
algorithm,
|
159 |
+
(
|
160 |
+
hashes.SHA1,
|
161 |
+
hashes.SHA224,
|
162 |
+
hashes.SHA256,
|
163 |
+
hashes.SHA384,
|
164 |
+
hashes.SHA512,
|
165 |
+
),
|
166 |
+
)
|
167 |
+
|
168 |
+
def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool:
|
169 |
+
if isinstance(padding, PKCS1v15):
|
170 |
+
return True
|
171 |
+
elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):
|
172 |
+
# SHA1 is permissible in MGF1 in FIPS even when SHA1 is blocked
|
173 |
+
# as signature algorithm.
|
174 |
+
if self._fips_enabled and isinstance(
|
175 |
+
padding._mgf._algorithm, hashes.SHA1
|
176 |
+
):
|
177 |
+
return True
|
178 |
+
else:
|
179 |
+
return self.hash_supported(padding._mgf._algorithm)
|
180 |
+
elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):
|
181 |
+
return self._oaep_hash_supported(
|
182 |
+
padding._mgf._algorithm
|
183 |
+
) and self._oaep_hash_supported(padding._algorithm)
|
184 |
+
else:
|
185 |
+
return False
|
186 |
+
|
187 |
+
def rsa_encryption_supported(self, padding: AsymmetricPadding) -> bool:
|
188 |
+
if self._fips_enabled and isinstance(padding, PKCS1v15):
|
189 |
+
return False
|
190 |
+
else:
|
191 |
+
return self.rsa_padding_supported(padding)
|
192 |
+
|
193 |
+
def dsa_supported(self) -> bool:
|
194 |
+
return (
|
195 |
+
not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
|
196 |
+
and not self._fips_enabled
|
197 |
+
)
|
198 |
+
|
199 |
+
def dsa_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
|
200 |
+
if not self.dsa_supported():
|
201 |
+
return False
|
202 |
+
return self.signature_hash_supported(algorithm)
|
203 |
+
|
204 |
+
def cmac_algorithm_supported(self, algorithm) -> bool:
|
205 |
+
return self.cipher_supported(
|
206 |
+
algorithm, CBC(b"\x00" * algorithm.block_size)
|
207 |
+
)
|
208 |
+
|
209 |
+
def elliptic_curve_supported(self, curve: ec.EllipticCurve) -> bool:
|
210 |
+
if self._fips_enabled and not isinstance(
|
211 |
+
curve, self._fips_ecdh_curves
|
212 |
+
):
|
213 |
+
return False
|
214 |
+
|
215 |
+
return rust_openssl.ec.curve_supported(curve)
|
216 |
+
|
217 |
+
def elliptic_curve_signature_algorithm_supported(
|
218 |
+
self,
|
219 |
+
signature_algorithm: ec.EllipticCurveSignatureAlgorithm,
|
220 |
+
curve: ec.EllipticCurve,
|
221 |
+
) -> bool:
|
222 |
+
# We only support ECDSA right now.
|
223 |
+
if not isinstance(signature_algorithm, ec.ECDSA):
|
224 |
+
return False
|
225 |
+
|
226 |
+
return self.elliptic_curve_supported(curve) and (
|
227 |
+
isinstance(signature_algorithm.algorithm, asym_utils.Prehashed)
|
228 |
+
or self.hash_supported(signature_algorithm.algorithm)
|
229 |
+
)
|
230 |
+
|
231 |
+
def elliptic_curve_exchange_algorithm_supported(
|
232 |
+
self, algorithm: ec.ECDH, curve: ec.EllipticCurve
|
233 |
+
) -> bool:
|
234 |
+
return self.elliptic_curve_supported(curve) and isinstance(
|
235 |
+
algorithm, ec.ECDH
|
236 |
+
)
|
237 |
+
|
238 |
+
def dh_supported(self) -> bool:
|
239 |
+
return not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
|
240 |
+
|
241 |
+
def dh_x942_serialization_supported(self) -> bool:
|
242 |
+
return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1
|
243 |
+
|
244 |
+
def x25519_supported(self) -> bool:
|
245 |
+
if self._fips_enabled:
|
246 |
+
return False
|
247 |
+
return True
|
248 |
+
|
249 |
+
def x448_supported(self) -> bool:
|
250 |
+
if self._fips_enabled:
|
251 |
+
return False
|
252 |
+
return (
|
253 |
+
not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL
|
254 |
+
and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
|
255 |
+
)
|
256 |
+
|
257 |
+
def ed25519_supported(self) -> bool:
|
258 |
+
if self._fips_enabled:
|
259 |
+
return False
|
260 |
+
return True
|
261 |
+
|
262 |
+
def ed448_supported(self) -> bool:
|
263 |
+
if self._fips_enabled:
|
264 |
+
return False
|
265 |
+
return (
|
266 |
+
not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL
|
267 |
+
and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
|
268 |
+
)
|
269 |
+
|
270 |
+
def ecdsa_deterministic_supported(self) -> bool:
|
271 |
+
return (
|
272 |
+
rust_openssl.CRYPTOGRAPHY_OPENSSL_320_OR_GREATER
|
273 |
+
and not self._fips_enabled
|
274 |
+
)
|
275 |
+
|
276 |
+
def poly1305_supported(self) -> bool:
|
277 |
+
if self._fips_enabled:
|
278 |
+
return False
|
279 |
+
return True
|
280 |
+
|
281 |
+
def pkcs7_supported(self) -> bool:
|
282 |
+
return not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
|
283 |
+
|
284 |
+
|
285 |
+
backend = Backend()
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/__init__.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives import padding
|
8 |
+
|
9 |
+
def check_ansix923_padding(data: bytes) -> bool: ...
|
10 |
+
|
11 |
+
class PKCS7PaddingContext(padding.PaddingContext):
|
12 |
+
def __init__(self, block_size: int) -> None: ...
|
13 |
+
def update(self, data: bytes) -> bytes: ...
|
14 |
+
def finalize(self) -> bytes: ...
|
15 |
+
|
16 |
+
class PKCS7UnpaddingContext(padding.PaddingContext):
|
17 |
+
def __init__(self, block_size: int) -> None: ...
|
18 |
+
def update(self, data: bytes) -> bytes: ...
|
19 |
+
def finalize(self) -> bytes: ...
|
20 |
+
|
21 |
+
class ObjectIdentifier:
|
22 |
+
def __init__(self, val: str) -> None: ...
|
23 |
+
@property
|
24 |
+
def dotted_string(self) -> str: ...
|
25 |
+
@property
|
26 |
+
def _name(self) -> str: ...
|
27 |
+
|
28 |
+
T = typing.TypeVar("T")
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
lib = typing.Any
|
8 |
+
ffi = typing.Any
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
def decode_dss_signature(signature: bytes) -> tuple[int, int]: ...
|
6 |
+
def encode_dss_signature(r: int, s: int) -> bytes: ...
|
7 |
+
def parse_spki_for_data(data: bytes) -> bytes: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
class _Reasons:
|
6 |
+
BACKEND_MISSING_INTERFACE: _Reasons
|
7 |
+
UNSUPPORTED_HASH: _Reasons
|
8 |
+
UNSUPPORTED_CIPHER: _Reasons
|
9 |
+
UNSUPPORTED_PADDING: _Reasons
|
10 |
+
UNSUPPORTED_MGF: _Reasons
|
11 |
+
UNSUPPORTED_PUBLIC_KEY_ALGORITHM: _Reasons
|
12 |
+
UNSUPPORTED_ELLIPTIC_CURVE: _Reasons
|
13 |
+
UNSUPPORTED_SERIALIZATION: _Reasons
|
14 |
+
UNSUPPORTED_X509: _Reasons
|
15 |
+
UNSUPPORTED_EXCHANGE_ALGORITHM: _Reasons
|
16 |
+
UNSUPPORTED_DIFFIE_HELLMAN: _Reasons
|
17 |
+
UNSUPPORTED_MAC: _Reasons
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import datetime
|
6 |
+
import typing
|
7 |
+
|
8 |
+
from cryptography import x509
|
9 |
+
from cryptography.hazmat.primitives import hashes, serialization
|
10 |
+
from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes
|
11 |
+
from cryptography.x509 import ocsp
|
12 |
+
|
13 |
+
class OCSPRequest:
|
14 |
+
@property
|
15 |
+
def issuer_key_hash(self) -> bytes: ...
|
16 |
+
@property
|
17 |
+
def issuer_name_hash(self) -> bytes: ...
|
18 |
+
@property
|
19 |
+
def hash_algorithm(self) -> hashes.HashAlgorithm: ...
|
20 |
+
@property
|
21 |
+
def serial_number(self) -> int: ...
|
22 |
+
def public_bytes(self, encoding: serialization.Encoding) -> bytes: ...
|
23 |
+
@property
|
24 |
+
def extensions(self) -> x509.Extensions: ...
|
25 |
+
|
26 |
+
class OCSPResponse:
|
27 |
+
@property
|
28 |
+
def responses(self) -> typing.Iterator[OCSPSingleResponse]: ...
|
29 |
+
@property
|
30 |
+
def response_status(self) -> ocsp.OCSPResponseStatus: ...
|
31 |
+
@property
|
32 |
+
def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ...
|
33 |
+
@property
|
34 |
+
def signature_hash_algorithm(
|
35 |
+
self,
|
36 |
+
) -> hashes.HashAlgorithm | None: ...
|
37 |
+
@property
|
38 |
+
def signature(self) -> bytes: ...
|
39 |
+
@property
|
40 |
+
def tbs_response_bytes(self) -> bytes: ...
|
41 |
+
@property
|
42 |
+
def certificates(self) -> list[x509.Certificate]: ...
|
43 |
+
@property
|
44 |
+
def responder_key_hash(self) -> bytes | None: ...
|
45 |
+
@property
|
46 |
+
def responder_name(self) -> x509.Name | None: ...
|
47 |
+
@property
|
48 |
+
def produced_at(self) -> datetime.datetime: ...
|
49 |
+
@property
|
50 |
+
def produced_at_utc(self) -> datetime.datetime: ...
|
51 |
+
@property
|
52 |
+
def certificate_status(self) -> ocsp.OCSPCertStatus: ...
|
53 |
+
@property
|
54 |
+
def revocation_time(self) -> datetime.datetime | None: ...
|
55 |
+
@property
|
56 |
+
def revocation_time_utc(self) -> datetime.datetime | None: ...
|
57 |
+
@property
|
58 |
+
def revocation_reason(self) -> x509.ReasonFlags | None: ...
|
59 |
+
@property
|
60 |
+
def this_update(self) -> datetime.datetime: ...
|
61 |
+
@property
|
62 |
+
def this_update_utc(self) -> datetime.datetime: ...
|
63 |
+
@property
|
64 |
+
def next_update(self) -> datetime.datetime | None: ...
|
65 |
+
@property
|
66 |
+
def next_update_utc(self) -> datetime.datetime | None: ...
|
67 |
+
@property
|
68 |
+
def issuer_key_hash(self) -> bytes: ...
|
69 |
+
@property
|
70 |
+
def issuer_name_hash(self) -> bytes: ...
|
71 |
+
@property
|
72 |
+
def hash_algorithm(self) -> hashes.HashAlgorithm: ...
|
73 |
+
@property
|
74 |
+
def serial_number(self) -> int: ...
|
75 |
+
@property
|
76 |
+
def extensions(self) -> x509.Extensions: ...
|
77 |
+
@property
|
78 |
+
def single_extensions(self) -> x509.Extensions: ...
|
79 |
+
def public_bytes(self, encoding: serialization.Encoding) -> bytes: ...
|
80 |
+
|
81 |
+
class OCSPSingleResponse:
|
82 |
+
@property
|
83 |
+
def certificate_status(self) -> ocsp.OCSPCertStatus: ...
|
84 |
+
@property
|
85 |
+
def revocation_time(self) -> datetime.datetime | None: ...
|
86 |
+
@property
|
87 |
+
def revocation_time_utc(self) -> datetime.datetime | None: ...
|
88 |
+
@property
|
89 |
+
def revocation_reason(self) -> x509.ReasonFlags | None: ...
|
90 |
+
@property
|
91 |
+
def this_update(self) -> datetime.datetime: ...
|
92 |
+
@property
|
93 |
+
def this_update_utc(self) -> datetime.datetime: ...
|
94 |
+
@property
|
95 |
+
def next_update(self) -> datetime.datetime | None: ...
|
96 |
+
@property
|
97 |
+
def next_update_utc(self) -> datetime.datetime | None: ...
|
98 |
+
@property
|
99 |
+
def issuer_key_hash(self) -> bytes: ...
|
100 |
+
@property
|
101 |
+
def issuer_name_hash(self) -> bytes: ...
|
102 |
+
@property
|
103 |
+
def hash_algorithm(self) -> hashes.HashAlgorithm: ...
|
104 |
+
@property
|
105 |
+
def serial_number(self) -> int: ...
|
106 |
+
|
107 |
+
def load_der_ocsp_request(data: bytes) -> ocsp.OCSPRequest: ...
|
108 |
+
def load_der_ocsp_response(data: bytes) -> ocsp.OCSPResponse: ...
|
109 |
+
def create_ocsp_request(
|
110 |
+
builder: ocsp.OCSPRequestBuilder,
|
111 |
+
) -> ocsp.OCSPRequest: ...
|
112 |
+
def create_ocsp_response(
|
113 |
+
status: ocsp.OCSPResponseStatus,
|
114 |
+
builder: ocsp.OCSPResponseBuilder | None,
|
115 |
+
private_key: PrivateKeyTypes | None,
|
116 |
+
hash_algorithm: hashes.HashAlgorithm | None,
|
117 |
+
) -> ocsp.OCSPResponse: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.bindings._rust.openssl import (
|
8 |
+
aead,
|
9 |
+
ciphers,
|
10 |
+
cmac,
|
11 |
+
dh,
|
12 |
+
dsa,
|
13 |
+
ec,
|
14 |
+
ed448,
|
15 |
+
ed25519,
|
16 |
+
hashes,
|
17 |
+
hmac,
|
18 |
+
kdf,
|
19 |
+
keys,
|
20 |
+
poly1305,
|
21 |
+
rsa,
|
22 |
+
x448,
|
23 |
+
x25519,
|
24 |
+
)
|
25 |
+
|
26 |
+
__all__ = [
|
27 |
+
"aead",
|
28 |
+
"ciphers",
|
29 |
+
"cmac",
|
30 |
+
"dh",
|
31 |
+
"dsa",
|
32 |
+
"ec",
|
33 |
+
"ed448",
|
34 |
+
"ed25519",
|
35 |
+
"hashes",
|
36 |
+
"hmac",
|
37 |
+
"kdf",
|
38 |
+
"keys",
|
39 |
+
"openssl_version",
|
40 |
+
"openssl_version_text",
|
41 |
+
"poly1305",
|
42 |
+
"raise_openssl_error",
|
43 |
+
"rsa",
|
44 |
+
"x448",
|
45 |
+
"x25519",
|
46 |
+
]
|
47 |
+
|
48 |
+
CRYPTOGRAPHY_IS_LIBRESSL: bool
|
49 |
+
CRYPTOGRAPHY_IS_BORINGSSL: bool
|
50 |
+
CRYPTOGRAPHY_OPENSSL_300_OR_GREATER: bool
|
51 |
+
CRYPTOGRAPHY_OPENSSL_309_OR_GREATER: bool
|
52 |
+
CRYPTOGRAPHY_OPENSSL_320_OR_GREATER: bool
|
53 |
+
|
54 |
+
class Providers: ...
|
55 |
+
|
56 |
+
_legacy_provider_loaded: bool
|
57 |
+
_providers: Providers
|
58 |
+
|
59 |
+
def openssl_version() -> int: ...
|
60 |
+
def openssl_version_text() -> str: ...
|
61 |
+
def raise_openssl_error() -> typing.NoReturn: ...
|
62 |
+
def capture_error_stack() -> list[OpenSSLError]: ...
|
63 |
+
def is_fips_enabled() -> bool: ...
|
64 |
+
def enable_fips(providers: Providers) -> None: ...
|
65 |
+
|
66 |
+
class OpenSSLError:
|
67 |
+
@property
|
68 |
+
def lib(self) -> int: ...
|
69 |
+
@property
|
70 |
+
def reason(self) -> int: ...
|
71 |
+
@property
|
72 |
+
def reason_text(self) -> bytes: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
class AESGCM:
|
6 |
+
def __init__(self, key: bytes) -> None: ...
|
7 |
+
@staticmethod
|
8 |
+
def generate_key(key_size: int) -> bytes: ...
|
9 |
+
def encrypt(
|
10 |
+
self,
|
11 |
+
nonce: bytes,
|
12 |
+
data: bytes,
|
13 |
+
associated_data: bytes | None,
|
14 |
+
) -> bytes: ...
|
15 |
+
def decrypt(
|
16 |
+
self,
|
17 |
+
nonce: bytes,
|
18 |
+
data: bytes,
|
19 |
+
associated_data: bytes | None,
|
20 |
+
) -> bytes: ...
|
21 |
+
|
22 |
+
class ChaCha20Poly1305:
|
23 |
+
def __init__(self, key: bytes) -> None: ...
|
24 |
+
@staticmethod
|
25 |
+
def generate_key() -> bytes: ...
|
26 |
+
def encrypt(
|
27 |
+
self,
|
28 |
+
nonce: bytes,
|
29 |
+
data: bytes,
|
30 |
+
associated_data: bytes | None,
|
31 |
+
) -> bytes: ...
|
32 |
+
def decrypt(
|
33 |
+
self,
|
34 |
+
nonce: bytes,
|
35 |
+
data: bytes,
|
36 |
+
associated_data: bytes | None,
|
37 |
+
) -> bytes: ...
|
38 |
+
|
39 |
+
class AESCCM:
|
40 |
+
def __init__(self, key: bytes, tag_length: int = 16) -> None: ...
|
41 |
+
@staticmethod
|
42 |
+
def generate_key(key_size: int) -> bytes: ...
|
43 |
+
def encrypt(
|
44 |
+
self,
|
45 |
+
nonce: bytes,
|
46 |
+
data: bytes,
|
47 |
+
associated_data: bytes | None,
|
48 |
+
) -> bytes: ...
|
49 |
+
def decrypt(
|
50 |
+
self,
|
51 |
+
nonce: bytes,
|
52 |
+
data: bytes,
|
53 |
+
associated_data: bytes | None,
|
54 |
+
) -> bytes: ...
|
55 |
+
|
56 |
+
class AESSIV:
|
57 |
+
def __init__(self, key: bytes) -> None: ...
|
58 |
+
@staticmethod
|
59 |
+
def generate_key(key_size: int) -> bytes: ...
|
60 |
+
def encrypt(
|
61 |
+
self,
|
62 |
+
data: bytes,
|
63 |
+
associated_data: list[bytes] | None,
|
64 |
+
) -> bytes: ...
|
65 |
+
def decrypt(
|
66 |
+
self,
|
67 |
+
data: bytes,
|
68 |
+
associated_data: list[bytes] | None,
|
69 |
+
) -> bytes: ...
|
70 |
+
|
71 |
+
class AESOCB3:
|
72 |
+
def __init__(self, key: bytes) -> None: ...
|
73 |
+
@staticmethod
|
74 |
+
def generate_key(key_size: int) -> bytes: ...
|
75 |
+
def encrypt(
|
76 |
+
self,
|
77 |
+
nonce: bytes,
|
78 |
+
data: bytes,
|
79 |
+
associated_data: bytes | None,
|
80 |
+
) -> bytes: ...
|
81 |
+
def decrypt(
|
82 |
+
self,
|
83 |
+
nonce: bytes,
|
84 |
+
data: bytes,
|
85 |
+
associated_data: bytes | None,
|
86 |
+
) -> bytes: ...
|
87 |
+
|
88 |
+
class AESGCMSIV:
|
89 |
+
def __init__(self, key: bytes) -> None: ...
|
90 |
+
@staticmethod
|
91 |
+
def generate_key(key_size: int) -> bytes: ...
|
92 |
+
def encrypt(
|
93 |
+
self,
|
94 |
+
nonce: bytes,
|
95 |
+
data: bytes,
|
96 |
+
associated_data: bytes | None,
|
97 |
+
) -> bytes: ...
|
98 |
+
def decrypt(
|
99 |
+
self,
|
100 |
+
nonce: bytes,
|
101 |
+
data: bytes,
|
102 |
+
associated_data: bytes | None,
|
103 |
+
) -> bytes: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives import ciphers
|
8 |
+
from cryptography.hazmat.primitives.ciphers import modes
|
9 |
+
|
10 |
+
@typing.overload
|
11 |
+
def create_encryption_ctx(
|
12 |
+
algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag
|
13 |
+
) -> ciphers.AEADEncryptionContext: ...
|
14 |
+
@typing.overload
|
15 |
+
def create_encryption_ctx(
|
16 |
+
algorithm: ciphers.CipherAlgorithm, mode: modes.Mode
|
17 |
+
) -> ciphers.CipherContext: ...
|
18 |
+
@typing.overload
|
19 |
+
def create_decryption_ctx(
|
20 |
+
algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag
|
21 |
+
) -> ciphers.AEADDecryptionContext: ...
|
22 |
+
@typing.overload
|
23 |
+
def create_decryption_ctx(
|
24 |
+
algorithm: ciphers.CipherAlgorithm, mode: modes.Mode
|
25 |
+
) -> ciphers.CipherContext: ...
|
26 |
+
def cipher_supported(
|
27 |
+
algorithm: ciphers.CipherAlgorithm, mode: modes.Mode
|
28 |
+
) -> bool: ...
|
29 |
+
def _advance(
|
30 |
+
ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int
|
31 |
+
) -> None: ...
|
32 |
+
def _advance_aad(
|
33 |
+
ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int
|
34 |
+
) -> None: ...
|
35 |
+
|
36 |
+
class CipherContext: ...
|
37 |
+
class AEADEncryptionContext: ...
|
38 |
+
class AEADDecryptionContext: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives import ciphers
|
8 |
+
|
9 |
+
class CMAC:
|
10 |
+
def __init__(
|
11 |
+
self,
|
12 |
+
algorithm: ciphers.BlockCipherAlgorithm,
|
13 |
+
backend: typing.Any = None,
|
14 |
+
) -> None: ...
|
15 |
+
def update(self, data: bytes) -> None: ...
|
16 |
+
def finalize(self) -> bytes: ...
|
17 |
+
def verify(self, signature: bytes) -> None: ...
|
18 |
+
def copy(self) -> CMAC: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives.asymmetric import dh
|
8 |
+
|
9 |
+
MIN_MODULUS_SIZE: int
|
10 |
+
|
11 |
+
class DHPrivateKey: ...
|
12 |
+
class DHPublicKey: ...
|
13 |
+
class DHParameters: ...
|
14 |
+
|
15 |
+
class DHPrivateNumbers:
|
16 |
+
def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ...
|
17 |
+
def private_key(self, backend: typing.Any = None) -> dh.DHPrivateKey: ...
|
18 |
+
@property
|
19 |
+
def x(self) -> int: ...
|
20 |
+
@property
|
21 |
+
def public_numbers(self) -> DHPublicNumbers: ...
|
22 |
+
|
23 |
+
class DHPublicNumbers:
|
24 |
+
def __init__(
|
25 |
+
self, y: int, parameter_numbers: DHParameterNumbers
|
26 |
+
) -> None: ...
|
27 |
+
def public_key(self, backend: typing.Any = None) -> dh.DHPublicKey: ...
|
28 |
+
@property
|
29 |
+
def y(self) -> int: ...
|
30 |
+
@property
|
31 |
+
def parameter_numbers(self) -> DHParameterNumbers: ...
|
32 |
+
|
33 |
+
class DHParameterNumbers:
|
34 |
+
def __init__(self, p: int, g: int, q: int | None = None) -> None: ...
|
35 |
+
def parameters(self, backend: typing.Any = None) -> dh.DHParameters: ...
|
36 |
+
@property
|
37 |
+
def p(self) -> int: ...
|
38 |
+
@property
|
39 |
+
def g(self) -> int: ...
|
40 |
+
@property
|
41 |
+
def q(self) -> int | None: ...
|
42 |
+
|
43 |
+
def generate_parameters(
|
44 |
+
generator: int, key_size: int, backend: typing.Any = None
|
45 |
+
) -> dh.DHParameters: ...
|
46 |
+
def from_pem_parameters(
|
47 |
+
data: bytes, backend: typing.Any = None
|
48 |
+
) -> dh.DHParameters: ...
|
49 |
+
def from_der_parameters(
|
50 |
+
data: bytes, backend: typing.Any = None
|
51 |
+
) -> dh.DHParameters: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives.asymmetric import dsa
|
8 |
+
|
9 |
+
class DSAPrivateKey: ...
|
10 |
+
class DSAPublicKey: ...
|
11 |
+
class DSAParameters: ...
|
12 |
+
|
13 |
+
class DSAPrivateNumbers:
|
14 |
+
def __init__(self, x: int, public_numbers: DSAPublicNumbers) -> None: ...
|
15 |
+
@property
|
16 |
+
def x(self) -> int: ...
|
17 |
+
@property
|
18 |
+
def public_numbers(self) -> DSAPublicNumbers: ...
|
19 |
+
def private_key(self, backend: typing.Any = None) -> dsa.DSAPrivateKey: ...
|
20 |
+
|
21 |
+
class DSAPublicNumbers:
|
22 |
+
def __init__(
|
23 |
+
self, y: int, parameter_numbers: DSAParameterNumbers
|
24 |
+
) -> None: ...
|
25 |
+
@property
|
26 |
+
def y(self) -> int: ...
|
27 |
+
@property
|
28 |
+
def parameter_numbers(self) -> DSAParameterNumbers: ...
|
29 |
+
def public_key(self, backend: typing.Any = None) -> dsa.DSAPublicKey: ...
|
30 |
+
|
31 |
+
class DSAParameterNumbers:
|
32 |
+
def __init__(self, p: int, q: int, g: int) -> None: ...
|
33 |
+
@property
|
34 |
+
def p(self) -> int: ...
|
35 |
+
@property
|
36 |
+
def q(self) -> int: ...
|
37 |
+
@property
|
38 |
+
def g(self) -> int: ...
|
39 |
+
def parameters(self, backend: typing.Any = None) -> dsa.DSAParameters: ...
|
40 |
+
|
41 |
+
def generate_parameters(key_size: int) -> dsa.DSAParameters: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives.asymmetric import ec
|
8 |
+
|
9 |
+
class ECPrivateKey: ...
|
10 |
+
class ECPublicKey: ...
|
11 |
+
|
12 |
+
class EllipticCurvePrivateNumbers:
|
13 |
+
def __init__(
|
14 |
+
self, private_value: int, public_numbers: EllipticCurvePublicNumbers
|
15 |
+
) -> None: ...
|
16 |
+
def private_key(
|
17 |
+
self, backend: typing.Any = None
|
18 |
+
) -> ec.EllipticCurvePrivateKey: ...
|
19 |
+
@property
|
20 |
+
def private_value(self) -> int: ...
|
21 |
+
@property
|
22 |
+
def public_numbers(self) -> EllipticCurvePublicNumbers: ...
|
23 |
+
|
24 |
+
class EllipticCurvePublicNumbers:
|
25 |
+
def __init__(self, x: int, y: int, curve: ec.EllipticCurve) -> None: ...
|
26 |
+
def public_key(
|
27 |
+
self, backend: typing.Any = None
|
28 |
+
) -> ec.EllipticCurvePublicKey: ...
|
29 |
+
@property
|
30 |
+
def x(self) -> int: ...
|
31 |
+
@property
|
32 |
+
def y(self) -> int: ...
|
33 |
+
@property
|
34 |
+
def curve(self) -> ec.EllipticCurve: ...
|
35 |
+
def __eq__(self, other: object) -> bool: ...
|
36 |
+
|
37 |
+
def curve_supported(curve: ec.EllipticCurve) -> bool: ...
|
38 |
+
def generate_private_key(
|
39 |
+
curve: ec.EllipticCurve, backend: typing.Any = None
|
40 |
+
) -> ec.EllipticCurvePrivateKey: ...
|
41 |
+
def from_private_numbers(
|
42 |
+
numbers: ec.EllipticCurvePrivateNumbers,
|
43 |
+
) -> ec.EllipticCurvePrivateKey: ...
|
44 |
+
def from_public_numbers(
|
45 |
+
numbers: ec.EllipticCurvePublicNumbers,
|
46 |
+
) -> ec.EllipticCurvePublicKey: ...
|
47 |
+
def from_public_bytes(
|
48 |
+
curve: ec.EllipticCurve, data: bytes
|
49 |
+
) -> ec.EllipticCurvePublicKey: ...
|
50 |
+
def derive_private_key(
|
51 |
+
private_value: int, curve: ec.EllipticCurve
|
52 |
+
) -> ec.EllipticCurvePrivateKey: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
6 |
+
|
7 |
+
class Ed25519PrivateKey: ...
|
8 |
+
class Ed25519PublicKey: ...
|
9 |
+
|
10 |
+
def generate_key() -> ed25519.Ed25519PrivateKey: ...
|
11 |
+
def from_private_bytes(data: bytes) -> ed25519.Ed25519PrivateKey: ...
|
12 |
+
def from_public_bytes(data: bytes) -> ed25519.Ed25519PublicKey: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from cryptography.hazmat.primitives.asymmetric import ed448
|
6 |
+
|
7 |
+
class Ed448PrivateKey: ...
|
8 |
+
class Ed448PublicKey: ...
|
9 |
+
|
10 |
+
def generate_key() -> ed448.Ed448PrivateKey: ...
|
11 |
+
def from_private_bytes(data: bytes) -> ed448.Ed448PrivateKey: ...
|
12 |
+
def from_public_bytes(data: bytes) -> ed448.Ed448PublicKey: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives import hashes
|
8 |
+
|
9 |
+
class Hash(hashes.HashContext):
|
10 |
+
def __init__(
|
11 |
+
self, algorithm: hashes.HashAlgorithm, backend: typing.Any = None
|
12 |
+
) -> None: ...
|
13 |
+
@property
|
14 |
+
def algorithm(self) -> hashes.HashAlgorithm: ...
|
15 |
+
def update(self, data: bytes) -> None: ...
|
16 |
+
def finalize(self) -> bytes: ...
|
17 |
+
def copy(self) -> Hash: ...
|
18 |
+
|
19 |
+
def hash_supported(algorithm: hashes.HashAlgorithm) -> bool: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives import hashes
|
8 |
+
|
9 |
+
class HMAC(hashes.HashContext):
|
10 |
+
def __init__(
|
11 |
+
self,
|
12 |
+
key: bytes,
|
13 |
+
algorithm: hashes.HashAlgorithm,
|
14 |
+
backend: typing.Any = None,
|
15 |
+
) -> None: ...
|
16 |
+
@property
|
17 |
+
def algorithm(self) -> hashes.HashAlgorithm: ...
|
18 |
+
def update(self, data: bytes) -> None: ...
|
19 |
+
def finalize(self) -> bytes: ...
|
20 |
+
def verify(self, signature: bytes) -> None: ...
|
21 |
+
def copy(self) -> HMAC: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives.hashes import HashAlgorithm
|
8 |
+
|
9 |
+
def derive_pbkdf2_hmac(
|
10 |
+
key_material: bytes,
|
11 |
+
algorithm: HashAlgorithm,
|
12 |
+
salt: bytes,
|
13 |
+
iterations: int,
|
14 |
+
length: int,
|
15 |
+
) -> bytes: ...
|
16 |
+
|
17 |
+
class Scrypt:
|
18 |
+
def __init__(
|
19 |
+
self,
|
20 |
+
salt: bytes,
|
21 |
+
length: int,
|
22 |
+
n: int,
|
23 |
+
r: int,
|
24 |
+
p: int,
|
25 |
+
backend: typing.Any = None,
|
26 |
+
) -> None: ...
|
27 |
+
def derive(self, key_material: bytes) -> bytes: ...
|
28 |
+
def verify(self, key_material: bytes, expected_key: bytes) -> None: ...
|
29 |
+
|
30 |
+
class Argon2id:
|
31 |
+
def __init__(
|
32 |
+
self,
|
33 |
+
*,
|
34 |
+
salt: bytes,
|
35 |
+
length: int,
|
36 |
+
iterations: int,
|
37 |
+
lanes: int,
|
38 |
+
memory_cost: int,
|
39 |
+
ad: bytes | None = None,
|
40 |
+
secret: bytes | None = None,
|
41 |
+
) -> None: ...
|
42 |
+
def derive(self, key_material: bytes) -> bytes: ...
|
43 |
+
def verify(self, key_material: bytes, expected_key: bytes) -> None: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives.asymmetric.types import (
|
8 |
+
PrivateKeyTypes,
|
9 |
+
PublicKeyTypes,
|
10 |
+
)
|
11 |
+
|
12 |
+
def load_der_private_key(
|
13 |
+
data: bytes,
|
14 |
+
password: bytes | None,
|
15 |
+
backend: typing.Any = None,
|
16 |
+
*,
|
17 |
+
unsafe_skip_rsa_key_validation: bool = False,
|
18 |
+
) -> PrivateKeyTypes: ...
|
19 |
+
def load_pem_private_key(
|
20 |
+
data: bytes,
|
21 |
+
password: bytes | None,
|
22 |
+
backend: typing.Any = None,
|
23 |
+
*,
|
24 |
+
unsafe_skip_rsa_key_validation: bool = False,
|
25 |
+
) -> PrivateKeyTypes: ...
|
26 |
+
def load_der_public_key(
|
27 |
+
data: bytes,
|
28 |
+
backend: typing.Any = None,
|
29 |
+
) -> PublicKeyTypes: ...
|
30 |
+
def load_pem_public_key(
|
31 |
+
data: bytes,
|
32 |
+
backend: typing.Any = None,
|
33 |
+
) -> PublicKeyTypes: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
class Poly1305:
|
6 |
+
def __init__(self, key: bytes) -> None: ...
|
7 |
+
@staticmethod
|
8 |
+
def generate_tag(key: bytes, data: bytes) -> bytes: ...
|
9 |
+
@staticmethod
|
10 |
+
def verify_tag(key: bytes, data: bytes, tag: bytes) -> None: ...
|
11 |
+
def update(self, data: bytes) -> None: ...
|
12 |
+
def finalize(self) -> bytes: ...
|
13 |
+
def verify(self, tag: bytes) -> None: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
8 |
+
|
9 |
+
class RSAPrivateKey: ...
|
10 |
+
class RSAPublicKey: ...
|
11 |
+
|
12 |
+
class RSAPrivateNumbers:
|
13 |
+
def __init__(
|
14 |
+
self,
|
15 |
+
p: int,
|
16 |
+
q: int,
|
17 |
+
d: int,
|
18 |
+
dmp1: int,
|
19 |
+
dmq1: int,
|
20 |
+
iqmp: int,
|
21 |
+
public_numbers: RSAPublicNumbers,
|
22 |
+
) -> None: ...
|
23 |
+
@property
|
24 |
+
def p(self) -> int: ...
|
25 |
+
@property
|
26 |
+
def q(self) -> int: ...
|
27 |
+
@property
|
28 |
+
def d(self) -> int: ...
|
29 |
+
@property
|
30 |
+
def dmp1(self) -> int: ...
|
31 |
+
@property
|
32 |
+
def dmq1(self) -> int: ...
|
33 |
+
@property
|
34 |
+
def iqmp(self) -> int: ...
|
35 |
+
@property
|
36 |
+
def public_numbers(self) -> RSAPublicNumbers: ...
|
37 |
+
def private_key(
|
38 |
+
self,
|
39 |
+
backend: typing.Any = None,
|
40 |
+
*,
|
41 |
+
unsafe_skip_rsa_key_validation: bool = False,
|
42 |
+
) -> rsa.RSAPrivateKey: ...
|
43 |
+
|
44 |
+
class RSAPublicNumbers:
|
45 |
+
def __init__(self, e: int, n: int) -> None: ...
|
46 |
+
@property
|
47 |
+
def n(self) -> int: ...
|
48 |
+
@property
|
49 |
+
def e(self) -> int: ...
|
50 |
+
def public_key(self, backend: typing.Any = None) -> rsa.RSAPublicKey: ...
|
51 |
+
|
52 |
+
def generate_private_key(
|
53 |
+
public_exponent: int,
|
54 |
+
key_size: int,
|
55 |
+
) -> rsa.RSAPrivateKey: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from cryptography.hazmat.primitives.asymmetric import x25519
|
6 |
+
|
7 |
+
class X25519PrivateKey: ...
|
8 |
+
class X25519PublicKey: ...
|
9 |
+
|
10 |
+
def generate_key() -> x25519.X25519PrivateKey: ...
|
11 |
+
def from_private_bytes(data: bytes) -> x25519.X25519PrivateKey: ...
|
12 |
+
def from_public_bytes(data: bytes) -> x25519.X25519PublicKey: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from cryptography.hazmat.primitives.asymmetric import x448
|
6 |
+
|
7 |
+
class X448PrivateKey: ...
|
8 |
+
class X448PublicKey: ...
|
9 |
+
|
10 |
+
def generate_key() -> x448.X448PrivateKey: ...
|
11 |
+
def from_private_bytes(data: bytes) -> x448.X448PrivateKey: ...
|
12 |
+
def from_public_bytes(data: bytes) -> x448.X448PublicKey: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography import x509
|
8 |
+
from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes
|
9 |
+
from cryptography.hazmat.primitives.serialization import (
|
10 |
+
KeySerializationEncryption,
|
11 |
+
)
|
12 |
+
from cryptography.hazmat.primitives.serialization.pkcs12 import (
|
13 |
+
PKCS12KeyAndCertificates,
|
14 |
+
PKCS12PrivateKeyTypes,
|
15 |
+
)
|
16 |
+
|
17 |
+
class PKCS12Certificate:
|
18 |
+
def __init__(
|
19 |
+
self, cert: x509.Certificate, friendly_name: bytes | None
|
20 |
+
) -> None: ...
|
21 |
+
@property
|
22 |
+
def friendly_name(self) -> bytes | None: ...
|
23 |
+
@property
|
24 |
+
def certificate(self) -> x509.Certificate: ...
|
25 |
+
|
26 |
+
def load_key_and_certificates(
|
27 |
+
data: bytes,
|
28 |
+
password: bytes | None,
|
29 |
+
backend: typing.Any = None,
|
30 |
+
) -> tuple[
|
31 |
+
PrivateKeyTypes | None,
|
32 |
+
x509.Certificate | None,
|
33 |
+
list[x509.Certificate],
|
34 |
+
]: ...
|
35 |
+
def load_pkcs12(
|
36 |
+
data: bytes,
|
37 |
+
password: bytes | None,
|
38 |
+
backend: typing.Any = None,
|
39 |
+
) -> PKCS12KeyAndCertificates: ...
|
40 |
+
def serialize_key_and_certificates(
|
41 |
+
name: bytes | None,
|
42 |
+
key: PKCS12PrivateKeyTypes | None,
|
43 |
+
cert: x509.Certificate | None,
|
44 |
+
cas: typing.Iterable[x509.Certificate | PKCS12Certificate] | None,
|
45 |
+
encryption_algorithm: KeySerializationEncryption,
|
46 |
+
) -> bytes: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
import typing
|
6 |
+
|
7 |
+
from cryptography import x509
|
8 |
+
from cryptography.hazmat.primitives import serialization
|
9 |
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
10 |
+
from cryptography.hazmat.primitives.serialization import pkcs7
|
11 |
+
|
12 |
+
def serialize_certificates(
|
13 |
+
certs: list[x509.Certificate],
|
14 |
+
encoding: serialization.Encoding,
|
15 |
+
) -> bytes: ...
|
16 |
+
def encrypt_and_serialize(
|
17 |
+
builder: pkcs7.PKCS7EnvelopeBuilder,
|
18 |
+
encoding: serialization.Encoding,
|
19 |
+
options: typing.Iterable[pkcs7.PKCS7Options],
|
20 |
+
) -> bytes: ...
|
21 |
+
def sign_and_serialize(
|
22 |
+
builder: pkcs7.PKCS7SignatureBuilder,
|
23 |
+
encoding: serialization.Encoding,
|
24 |
+
options: typing.Iterable[pkcs7.PKCS7Options],
|
25 |
+
) -> bytes: ...
|
26 |
+
def decrypt_der(
|
27 |
+
data: bytes,
|
28 |
+
certificate: x509.Certificate,
|
29 |
+
private_key: rsa.RSAPrivateKey,
|
30 |
+
options: typing.Iterable[pkcs7.PKCS7Options],
|
31 |
+
) -> bytes: ...
|
32 |
+
def decrypt_pem(
|
33 |
+
data: bytes,
|
34 |
+
certificate: x509.Certificate,
|
35 |
+
private_key: rsa.RSAPrivateKey,
|
36 |
+
options: typing.Iterable[pkcs7.PKCS7Options],
|
37 |
+
) -> bytes: ...
|
38 |
+
def decrypt_smime(
|
39 |
+
data: bytes,
|
40 |
+
certificate: x509.Certificate,
|
41 |
+
private_key: rsa.RSAPrivateKey,
|
42 |
+
options: typing.Iterable[pkcs7.PKCS7Options],
|
43 |
+
) -> bytes: ...
|
44 |
+
def load_pem_pkcs7_certificates(
|
45 |
+
data: bytes,
|
46 |
+
) -> list[x509.Certificate]: ...
|
47 |
+
def load_der_pkcs7_certificates(
|
48 |
+
data: bytes,
|
49 |
+
) -> list[x509.Certificate]: ...
|
lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
+
# for complete details.
|
4 |
+
|
5 |
+
from cryptography import x509
|
6 |
+
from cryptography.hazmat.primitives import serialization
|
7 |
+
from cryptography.hazmat.primitives.serialization import pkcs7
|
8 |
+
|
9 |
+
class TestCertificate:
|
10 |
+
not_after_tag: int
|
11 |
+
not_before_tag: int
|
12 |
+
issuer_value_tags: list[int]
|
13 |
+
subject_value_tags: list[int]
|
14 |
+
|
15 |
+
def test_parse_certificate(data: bytes) -> TestCertificate: ...
|
16 |
+
def pkcs7_verify(
|
17 |
+
encoding: serialization.Encoding,
|
18 |
+
sig: bytes,
|
19 |
+
msg: bytes | None,
|
20 |
+
certs: list[x509.Certificate],
|
21 |
+
options: list[pkcs7.PKCS7Options],
|
22 |
+
) -> None: ...
|