_global_data = None
_default_plural_rule = PluralRule({})
+
def _raise_no_data_error():
raise RuntimeError('The babel data files are not available. '
'This usually happens because you are using '
month_idx = format_str.index('l')
day_idx = format_str.index('d')
- indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
- indexes.sort()
+ indexes = sorted([(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')])
indexes = {item[1]: idx for idx, item in enumerate(indexes)}
# FIXME: this currently only supports numbers, but should also support month
min_idx = format_str.index('m')
sec_idx = format_str.index('s')
- indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')]
- indexes.sort()
+ indexes = sorted([(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')])
indexes = {item[1]: idx for idx, item in enumerate(indexes)}
# TODO: support time zones
return pat
def __mod__(self, other: DateTimeFormat) -> str:
- if type(other) is not DateTimeFormat:
+ if not isinstance(other, DateTimeFormat):
return NotImplemented
return self.format % other
:param pattern: the formatting pattern to parse
"""
- if type(pattern) is DateTimePattern:
+ if isinstance(pattern, DateTimePattern):
return pattern
if pattern in _pattern_cache:
return None
+
def _get_tzinfo_or_raise(tzenv: str):
tzinfo = _get_tzinfo(tzenv)
if tzinfo is None:
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#"""
+
def parse_separated_header(value: str) -> dict[str, str]:
# Adapted from https://peps.python.org/pep-0594/#cgi
from email.message import Message
if key in self._messages:
del self._messages[key]
- def update(self,
+ def update(
+ self,
template: Catalog,
no_fuzzy_matching: bool = False,
update_header_comment: bool = False,
DEFAULT_MAPPING: list[tuple[str, str]] = [('**.py', 'python')]
-
def _strip_comment_tags(comments: MutableSequence[str], tags: Iterable[str]):
"""Helper function for `extract` that strips comment tags from strings
in a list of comment lines. This functions operates in-place.
token = Token('operator', ')', token.lineno)
if options.get('parse_template_string') and not funcname and token.type == 'template_string':
- for item in parse_template_string(token.value, keywords, comment_tags, options, token.lineno):
- yield item
+ yield from parse_template_string(token.value, keywords, comment_tags, options, token.lineno)
elif token.type == 'operator' and token.value == '(':
if funcname:
if level == 0 and expression_contents:
expression_contents = expression_contents[0:-1]
fake_file_obj = io.BytesIO(expression_contents.encode())
- for item in extract_javascript(fake_file_obj, keywords, comment_tags, options, lineno):
- yield item
+ yield from extract_javascript(fake_file_obj, keywords, comment_tags, options, lineno)
lineno += len(line_re.findall(expression_contents))
expression_contents = ''
prev_character = character
from distutils.errors import DistutilsSetupError as SetupError
-
def listify_value(arg, split=None):
"""
Make a list out of an argument.
omit_header=self.omit_header,
ignore_obsolete=self.ignore_obsolete,
include_previous=self.previous, width=self.width)
- except:
+ except Exception:
os.remove(tmpname)
raise
uni_escape_re = re.compile(r'[a-fA-F0-9]{1,4}')
hex_escape_re = re.compile(r'[a-fA-F0-9]{1,2}')
+
class Token(NamedTuple):
type: str
value: str
lineno: int
+
_rules: list[tuple[str | None, re.Pattern[str]]] = [
(None, re.compile(r'\s+', re.UNICODE)),
(None, re.compile(r'<!--.*')),
add = result.append
pos = 0
- while 1:
+ while True:
# scan for the next escape
escape_pos = string.find('\\', pos)
if escape_pos < 0:
return self.__cmp__(other) != 0
-
class PoFileParser:
"""Support class to read messages from a ``gettext`` PO (portable object) file
and add them to a `Catalog`
locs.append(location)
_write_comment(' '.join(locs), prefix=':')
if message.flags:
- _write('#%s\n' % ', '.join([''] + sorted(message.flags)))
+ _write(f"#{', '.join(['', *sorted(message.flags)])}\n")
if message.previous_id and include_previous:
- _write_comment('msgid %s' % _normalize(message.previous_id[0]),
- prefix='|')
+ _write_comment(
+ f'msgid {_normalize(message.previous_id[0])}',
+ prefix='|',
+ )
if len(message.previous_id) > 1:
_write_comment('msgid_plural %s' % _normalize(
message.previous_id[1]
class RuleError(Exception):
"""Raised if a rule is malformed."""
+
_VARS = {
'n', # absolute value of the source number.
'i', # integer digits of n.
'Got unexpected %r' % s[pos])
return result[::-1]
+
def test_next_token(
tokens: list[tuple[str, str]],
type_: str,
from babel.dates import _PredefinedTimeFormat
+
class Format:
"""Wrapper class providing the various date and number formatting functions
bound to a specific locale and time-zone.
if TYPE_CHECKING:
from typing_extensions import Literal
+
class UnknownUnitError(ValueError):
def __init__(self, unit: str, locale: Locale) -> None:
ValueError.__init__(self, f"{unit} is not a known unit in {locale}")
_T = TypeVar("_T")
+
def distinct(iterable: Iterable[_T]) -> Generator[_T, None, None]:
"""Yield all items in an iterable collection that are distinct.
yield item
seen.add(item)
+
# Regexp to match python magic encoding line
PYTHON_MAGIC_COMMENT_re = re.compile(
br'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)', re.VERBOSE)
return False
h = hashlib.sha512()
with open(filename, 'rb') as f:
- while 1:
+ while True:
blk = f.read(BLKSIZE)
if not blk:
break
_import_type_text(measurement_systems, measurement_system, type=type)
-
if __name__ == '__main__':
main()
def test_update_message_changed_to_simple(self):
cat = catalog.Catalog()
- cat.add('foo' u'foos', ('Voh', 'Vöhs'))
+ cat.add('foo' 'foos', ('Voh', 'Vöhs'))
tmpl = catalog.Catalog()
tmpl.add('foo')
cat.update(tmpl)
assert cat['foo'].user_comments == []
# Update cat[u'foo'] with a new location and a comment
cat['foo'] = catalog.Message('foo', locations=[('main.py', 7)],
- user_comments=['Foo Bar comment 1'])
+ user_comments=['Foo Bar comment 1'])
assert cat['foo'].user_comments == ['Foo Bar comment 1']
# now add yet another location with another comment
cat['foo'] = catalog.Message('foo', locations=[('main.py', 9)],
- auto_comments=['Foo Bar comment 2'])
+ auto_comments=['Foo Bar comment 2'])
assert cat['foo'].auto_comments == ['Foo Bar comment 2']
def test_update_fuzzy_matching_with_case_change(self):
assert dates.DateTimeFormat(d, locale='en_US')['w'] == '53'
def test_week_of_year_de_first_us_last_with_year(self):
- d = date(2018,12,31)
+ d = date(2018, 12, 31)
fmt = dates.DateTimeFormat(d, locale='de_DE')
assert fmt['w'] == '1'
assert fmt['YYYY'] == '2019'
tzinfo=timezone_getter('Europe/Paris'),
locale='fr_FR'
)
- assert full == ('dimanche 1 avril 2007 à 17:30:00 heure '
- u'd\u2019\xe9t\xe9 d\u2019Europe centrale')
+ assert full == (
+ 'dimanche 1 avril 2007 à 17:30:00 heure '
+ 'd\u2019\xe9t\xe9 d\u2019Europe centrale'
+ )
custom = dates.format_datetime(
dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
tzinfo=timezone_getter('US/Eastern'),
def test_russian_week_numbering():
# See https://github.com/python-babel/babel/issues/485
v = date(2017, 1, 1)
- assert dates.format_date(v, format='YYYY-ww',locale='ru_RU') == '2016-52' # This would have returned 2017-01 prior to CLDR 32
- assert dates.format_date(v, format='YYYY-ww',locale='de_DE') == '2016-52'
+ assert dates.format_date(v, format='YYYY-ww', locale='ru_RU') == '2016-52' # This would have returned 2017-01 prior to CLDR 32
+ assert dates.format_date(v, format='YYYY-ww', locale='de_DE') == '2016-52'
def test_en_gb_first_weekday():
# Testing None input.
normalized_locale = localedata.normalize_locale(None)
assert normalized_locale is None
- locale_exist = localedata.exists(None)
- assert locale_exist is False
+ assert not localedata.exists(None)
- # # Testing list input.
+ # Testing list input.
normalized_locale = localedata.normalize_locale(['en_us', None])
assert normalized_locale is None
- locale_exist = localedata.exists(['en_us', None])
- assert locale_exist is False
+ assert not localedata.exists(['en_us', None])
def test_locale_identifiers_cache(monkeypatch):
original_listdir = localedata.os.listdir
listdir_calls = []
+
def listdir_spy(*args):
rv = original_listdir(*args)
listdir_calls.append((args, rv))
assert numbers.format_compact_decimal(1000, locale='fr', format_type='long') == 'mille'
assert numbers.format_compact_decimal(1234, locale='fr', format_type='long') == '1 millier'
+
class NumberParsingTestCase(unittest.TestCase):
def test_can_parse_decimals(self):
def test_is_currency():
- assert is_currency('EUR') is True
- assert is_currency('eUr') is False
- assert is_currency('FUU') is False
- assert is_currency('') is False
- assert is_currency(None) is False
- assert is_currency(' EUR ') is False
- assert is_currency(' ') is False
- assert is_currency([]) is False
- assert is_currency(set()) is False
+ assert is_currency('EUR')
+ assert not is_currency('eUr')
+ assert not is_currency('FUU')
+ assert not is_currency('')
+ assert not is_currency(None)
+ assert not is_currency(' EUR ')
+ assert not is_currency(' ')
+ assert not is_currency([])
+ assert not is_currency(set())
def test_normalize_currency():
def test_format_compact_currency_invalid_format_type():
with pytest.raises(numbers.UnknownCurrencyFormatError):
- numbers.format_compact_currency(1099.98, 'USD', locale='en_US',
- format_type='unknown')
+ numbers.format_compact_currency(1099.98, 'USD', locale='en_US', format_type='unknown')
@pytest.mark.parametrize('input_value, expected_value', [
SKIP_LGETTEXT = sys.version_info >= (3, 8)
+
@pytest.mark.usefixtures("os_environ")
class TranslationsTestCase(unittest.TestCase):
def test_upgettext(self):
self.assertEqualTypeToo('Voh', self.translations.ugettext('foo'))
self.assertEqualTypeToo('VohCTX', self.translations.upgettext('foo',
- 'foo'))
+ 'foo'))
@pytest.mark.skipif(SKIP_LGETTEXT, reason="lgettext is deprecated")
def test_lpgettext(self):
'VohsD1', self.translations.dungettext('messages1', 'foo1', 'foos1', 2))
self.assertEqualTypeToo(
'VohCTXD1', self.translations.dunpgettext('messages1', 'foo', 'foo1',
- 'foos1', 1))
+ 'foos1', 1))
self.assertEqualTypeToo(
'VohsCTXD1', self.translations.dunpgettext('messages1', 'foo', 'foo1',
- 'foos1', 2))
+ 'foos1', 2))
@pytest.mark.skipif(SKIP_LGETTEXT, reason="lgettext is deprecated")
def test_ldnpgettext(self):
assert '(%s)' % lazy_greeting == '(Hello, Joe!)'
assert f"[{lazy_greeting}]" == "[Hello, Joe!]"
- greetings = [
+ greetings = sorted([
support.LazyProxy(greeting, 'world'),
support.LazyProxy(greeting, 'Joe'),
support.LazyProxy(greeting, 'universe'),
- ]
- greetings.sort()
+ ])
assert [str(g) for g in greetings] == [
"Hello, Joe!",
"Hello, universe!",
class _FF:
- division = __future__.division.compiler_flag
- print_function = __future__.print_function.compiler_flag
- with_statement = __future__.with_statement.compiler_flag
+ division = __future__.division.compiler_flag
+ print_function = __future__.print_function.compiler_flag
+ with_statement = __future__.with_statement.compiler_flag
unicode_literals = __future__.unicode_literals.compiler_flag
+
def test_distinct():
assert list(util.distinct([1, 2, 1, 3, 4, 4])) == [1, 2, 3, 4]
assert list(util.distinct('foobar')) == ['f', 'o', 'b', 'a', 'r']
class FixedOffsetTimezoneTestCase(unittest.TestCase):
def test_zone_negative_offset(self):
- assert util.FixedOffsetTimezone((-60)).zone == 'Etc/GMT-60'
+ assert util.FixedOffsetTimezone(-60).zone == 'Etc/GMT-60'
def test_zone_zero_offset(self):
assert util.FixedOffsetTimezone(0).zone == 'Etc/GMT+0'