]> git.ipfire.org Git - thirdparty/babel.git/commitdiff
Apply some small miscellaneous formatting fixes
authorAarni Koskela <akx@iki.fi>
Wed, 18 Jan 2023 18:27:44 +0000 (20:27 +0200)
committerAarni Koskela <akx@iki.fi>
Wed, 18 Jan 2023 19:20:51 +0000 (21:20 +0200)
20 files changed:
babel/core.py
babel/dates.py
babel/localtime/_helpers.py
babel/messages/catalog.py
babel/messages/extract.py
babel/messages/frontend.py
babel/messages/jslexer.py
babel/messages/pofile.py
babel/plural.py
babel/support.py
babel/units.py
babel/util.py
scripts/download_import_cldr.py
scripts/import_cldr.py
tests/messages/test_catalog.py
tests/test_dates.py
tests/test_localedata.py
tests/test_numbers.py
tests/test_support.py
tests/test_util.py

index 604e5d9ee25978602e11a881f8fbceeb3fba40d3..ce564d75098740b126bf5942c08baf9fdefeca23 100644 (file)
@@ -46,6 +46,7 @@ if TYPE_CHECKING:
 _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 '
index 26766a6959041dfb6c5891cf1657d8d0593859a0..e626df5c2df43ee23dffd98ebf1915939e713f2f 100644 (file)
@@ -1349,8 +1349,7 @@ def parse_date(
         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
@@ -1399,8 +1398,7 @@ def parse_time(
     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
@@ -1436,7 +1434,7 @@ class DateTimePattern:
         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
 
@@ -1829,7 +1827,7 @@ def parse_pattern(pattern: str) -> DateTimePattern:
 
     :param pattern: the formatting pattern to parse
     """
-    if type(pattern) is DateTimePattern:
+    if isinstance(pattern, DateTimePattern):
         return pattern
 
     if pattern in _pattern_cache:
index b7238f6a68a390b515fb0ab5a297e1415647378f..159f9a5697c16847aaa99228cb6876093408fe91 100644 (file)
@@ -24,6 +24,7 @@ def _get_tzinfo(tzenv: str):
 
     return None
 
+
 def _get_tzinfo_or_raise(tzenv: str):
     tzinfo = _get_tzinfo(tzenv)
     if tzinfo is None:
index 85f16b259f959dfb274f13513f02e389f4d01d88..dead4aac7f95ccb589942ec0c2500b584c6ba806 100644 (file)
@@ -240,6 +240,7 @@ DEFAULT_HEADER = """\
 # 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
@@ -736,7 +737,8 @@ class Catalog:
         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,
index 0934937c82d2264cad064d65d846b492eaeb1bbf..453742ed03ac205d1f4c88ffb65b537b713a5e8e 100644 (file)
@@ -90,7 +90,6 @@ DEFAULT_KEYWORDS: dict[str, _Keyword] = {
 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.
@@ -660,8 +659,7 @@ def extract_javascript(
             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:
@@ -794,8 +792,7 @@ def parse_template_string(
                 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
index de17b1ea59dcea41eebe8b94a129e1661bedf547..ab094ecd448f77c1488f49620ba0ed7feb7391b9 100644 (file)
@@ -56,7 +56,6 @@ except ImportError:
     from distutils.errors import DistutilsSetupError as SetupError
 
 
-
 def listify_value(arg, split=None):
     """
     Make a list out of an argument.
@@ -853,7 +852,7 @@ class update_catalog(Command):
                              omit_header=self.omit_header,
                              ignore_obsolete=self.ignore_obsolete,
                              include_previous=self.previous, width=self.width)
-            except:
+            except Exception:
                 os.remove(tmpname)
                 raise
 
index d2ffbbe76150fd8fee1dd38845f3b5b67591e276..0563f62211ea7b3d612b1455d9b7284d75f6f60c 100644 (file)
@@ -32,11 +32,13 @@ line_join_re = re.compile(r'\\' + line_re.pattern)
 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'<!--.*')),
@@ -100,7 +102,7 @@ def unquote_string(string: str) -> str:
     add = result.append
     pos = 0
 
-    while 1:
+    while True:
         # scan for the next escape
         escape_pos = string.find('\\', pos)
         if escape_pos < 0:
index a9180a719a30f38eac01d7216c3a447f5da157e8..88cc0430f027332eca685bf55a7eed6464bf81d2 100644 (file)
@@ -134,7 +134,6 @@ class _NormalizedString:
         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`
@@ -615,11 +614,13 @@ def write_po(
                     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]
index fd0d0da5263c99db6b486fd75bdd92717d91953a..fe1ee2553522d101537f1fa3b0264c311eaf12b5 100644 (file)
@@ -325,6 +325,7 @@ def cldr_modulo(a: float, b: float) -> float:
 class RuleError(Exception):
     """Raised if a rule is malformed."""
 
+
 _VARS = {
     'n',  # absolute value of the source number.
     'i',  # integer digits of n.
@@ -363,6 +364,7 @@ def tokenize_rule(s: str) -> list[tuple[str, str]]:
                             'Got unexpected %r' % s[pos])
     return result[::-1]
 
+
 def test_next_token(
     tokens: list[tuple[str, str]],
     type_: str,
index 70925997ccd79e31e307af5cb6536ef6665c82c2..242b492bf8a44cbec573920e8e808d14963f0a49 100644 (file)
@@ -35,6 +35,7 @@ if TYPE_CHECKING:
 
     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.
index 1180bd1255f8379d5ded7baecff7c26593aafc76..0c72ee97aa96cd1bd999cb4546641c4cac9fd743 100644 (file)
@@ -9,6 +9,7 @@ from babel.numbers import LC_NUMERIC, format_decimal
 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}")
index cf86f20f54893ecdae655a4fa24fea6a2a72810f..a5403e6533924d2b31aa2ce49efb77ad04d097a8 100644 (file)
@@ -24,6 +24,7 @@ missing = object()
 
 _T = TypeVar("_T")
 
+
 def distinct(iterable: Iterable[_T]) -> Generator[_T, None, None]:
     """Yield all items in an iterable collection that are distinct.
 
@@ -43,6 +44,7 @@ def distinct(iterable: Iterable[_T]) -> Generator[_T, None, None]:
             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)
index 926e747609bb6dd03686fa5aa9c166fb91c1bfdb..ab455ac14cb178e396d1e9148a136dbdec1ef843 100755 (executable)
@@ -37,7 +37,7 @@ def is_good_file(filename):
         return False
     h = hashlib.sha512()
     with open(filename, 'rb') as f:
-        while 1:
+        while True:
             blk = f.read(BLKSIZE)
             if not blk:
                 break
index 33e4a60990e943d517fff979f783916bc2fe9ba1..5630ba8961cd40945c7495f991593a84c5b726c7 100755 (executable)
@@ -990,6 +990,5 @@ def parse_measurement_systems(data, tree):
             _import_type_text(measurement_systems, measurement_system, type=type)
 
 
-
 if __name__ == '__main__':
     main()
index 29cfc0d65a176c6b5c9633003809cbf60e458289..273c83f51c8bba0bffa1d753cc8fac0ed83b9a07 100644 (file)
@@ -98,7 +98,7 @@ class CatalogTestCase(unittest.TestCase):
 
     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)
@@ -112,11 +112,11 @@ class CatalogTestCase(unittest.TestCase):
         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):
index fd85a1b97908e003a9dc5038c2313e6aa65b37df..2e3c880c5e210ba83c919d85d690803b2faf8e5c 100644 (file)
@@ -68,7 +68,7 @@ class DateTimeFormatTestCase:
         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'
@@ -571,8 +571,10 @@ def test_format_datetime(timezone_getter):
         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'),
@@ -727,8 +729,8 @@ def test_no_inherit_metazone_formatting(timezone_getter):
 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():
index 7672ddc1516bc464cc7bd098c0d8ed1bcd428c83..36f3e7354dcaf743b94cfe1c62960f7a07becce3 100644 (file)
@@ -94,19 +94,18 @@ def test_locale_argument_acceptance():
     # 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))
index a6f79f01c46f29491a9d9062f5d298f3ca00b9d6..04a186510ef27a0150ab5259ed52de8eb6cd47cd 100644 (file)
@@ -167,6 +167,7 @@ class FormatDecimalTestCase(unittest.TestCase):
         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):
@@ -231,15 +232,15 @@ def test_validate_currency():
 
 
 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():
@@ -451,8 +452,7 @@ def test_format_compact_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', [
index 36bdcf665b5edc3608b1c78dae174e239654011d..0b7cba0674729b4ebcc0b77134acc018f653648a 100644 (file)
@@ -27,6 +27,7 @@ from babel.messages.mofile import write_mo
 
 SKIP_LGETTEXT = sys.version_info >= (3, 8)
 
+
 @pytest.mark.usefixtures("os_environ")
 class TranslationsTestCase(unittest.TestCase):
 
@@ -73,7 +74,7 @@ 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):
@@ -156,10 +157,10 @@ class TranslationsTestCase(unittest.TestCase):
             '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):
@@ -351,12 +352,11 @@ def test_lazy_proxy():
     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!",
index d21c723f3e4c480c9d237683df307d521872e343..ae861ddc0117022c44e583a2cd4a46f237e0bc0e 100644 (file)
@@ -22,11 +22,12 @@ from babel.util import parse_future_flags
 
 
 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']
@@ -48,7 +49,7 @@ def test_pathmatch():
 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'