summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAarni Koskela <akx@iki.fi>2023-01-18 20:27:44 +0200
committerAarni Koskela <akx@iki.fi>2023-01-18 21:20:51 +0200
commit82d345a66e850f643607ac9fcafd9b9a2a89d1e1 (patch)
treead66b7a13fb05f30628b6710dacab554505d55e8
parentcb0269fc63f5af4ade770f7a8872de8090bf697d (diff)
downloadbabel-82d345a66e850f643607ac9fcafd9b9a2a89d1e1.tar.gz
Apply some small miscellaneous formatting fixes
-rw-r--r--babel/core.py1
-rw-r--r--babel/dates.py10
-rw-r--r--babel/localtime/_helpers.py1
-rw-r--r--babel/messages/catalog.py4
-rw-r--r--babel/messages/extract.py7
-rw-r--r--babel/messages/frontend.py3
-rw-r--r--babel/messages/jslexer.py4
-rw-r--r--babel/messages/pofile.py9
-rw-r--r--babel/plural.py2
-rw-r--r--babel/support.py1
-rw-r--r--babel/units.py1
-rw-r--r--babel/util.py2
-rwxr-xr-xscripts/download_import_cldr.py2
-rwxr-xr-xscripts/import_cldr.py1
-rw-r--r--tests/messages/test_catalog.py6
-rw-r--r--tests/test_dates.py12
-rw-r--r--tests/test_localedata.py9
-rw-r--r--tests/test_numbers.py22
-rw-r--r--tests/test_support.py12
-rw-r--r--tests/test_util.py9
20 files changed, 63 insertions, 55 deletions
diff --git a/babel/core.py b/babel/core.py
index 604e5d9..ce564d7 100644
--- a/babel/core.py
+++ b/babel/core.py
@@ -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 '
diff --git a/babel/dates.py b/babel/dates.py
index 26766a6..e626df5 100644
--- a/babel/dates.py
+++ b/babel/dates.py
@@ -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:
diff --git a/babel/localtime/_helpers.py b/babel/localtime/_helpers.py
index b7238f6..159f9a5 100644
--- a/babel/localtime/_helpers.py
+++ b/babel/localtime/_helpers.py
@@ -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:
diff --git a/babel/messages/catalog.py b/babel/messages/catalog.py
index 85f16b2..dead4aa 100644
--- a/babel/messages/catalog.py
+++ b/babel/messages/catalog.py
@@ -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,
diff --git a/babel/messages/extract.py b/babel/messages/extract.py
index 0934937..453742e 100644
--- a/babel/messages/extract.py
+++ b/babel/messages/extract.py
@@ -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
diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py
index de17b1e..ab094ec 100644
--- a/babel/messages/frontend.py
+++ b/babel/messages/frontend.py
@@ -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
diff --git a/babel/messages/jslexer.py b/babel/messages/jslexer.py
index d2ffbbe..0563f62 100644
--- a/babel/messages/jslexer.py
+++ b/babel/messages/jslexer.py
@@ -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:
diff --git a/babel/messages/pofile.py b/babel/messages/pofile.py
index a9180a7..88cc043 100644
--- a/babel/messages/pofile.py
+++ b/babel/messages/pofile.py
@@ -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]
diff --git a/babel/plural.py b/babel/plural.py
index fd0d0da..fe1ee25 100644
--- a/babel/plural.py
+++ b/babel/plural.py
@@ -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,
diff --git a/babel/support.py b/babel/support.py
index 7092599..242b492 100644
--- a/babel/support.py
+++ b/babel/support.py
@@ -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.
diff --git a/babel/units.py b/babel/units.py
index 1180bd1..0c72ee9 100644
--- a/babel/units.py
+++ b/babel/units.py
@@ -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}")
diff --git a/babel/util.py b/babel/util.py
index cf86f20..a5403e6 100644
--- a/babel/util.py
+++ b/babel/util.py
@@ -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)
diff --git a/scripts/download_import_cldr.py b/scripts/download_import_cldr.py
index 926e747..ab455ac 100755
--- a/scripts/download_import_cldr.py
+++ b/scripts/download_import_cldr.py
@@ -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
diff --git a/scripts/import_cldr.py b/scripts/import_cldr.py
index 33e4a60..5630ba8 100755
--- a/scripts/import_cldr.py
+++ b/scripts/import_cldr.py
@@ -990,6 +990,5 @@ def parse_measurement_systems(data, tree):
_import_type_text(measurement_systems, measurement_system, type=type)
-
if __name__ == '__main__':
main()
diff --git a/tests/messages/test_catalog.py b/tests/messages/test_catalog.py
index 29cfc0d..273c83f 100644
--- a/tests/messages/test_catalog.py
+++ b/tests/messages/test_catalog.py
@@ -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):
diff --git a/tests/test_dates.py b/tests/test_dates.py
index fd85a1b..2e3c880 100644
--- a/tests/test_dates.py
+++ b/tests/test_dates.py
@@ -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():
diff --git a/tests/test_localedata.py b/tests/test_localedata.py
index 7672ddc..36f3e73 100644
--- a/tests/test_localedata.py
+++ b/tests/test_localedata.py
@@ -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))
diff --git a/tests/test_numbers.py b/tests/test_numbers.py
index a6f79f0..04a1865 100644
--- a/tests/test_numbers.py
+++ b/tests/test_numbers.py
@@ -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', [
diff --git a/tests/test_support.py b/tests/test_support.py
index 36bdcf6..0b7cba0 100644
--- a/tests/test_support.py
+++ b/tests/test_support.py
@@ -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!",
diff --git a/tests/test_util.py b/tests/test_util.py
index d21c723..ae861dd 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -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'