Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Apply some changes suggested by flake8
  • Loading branch information
akx committed Jan 11, 2023
commit 6cf1a56ebd261dfd5e91c1f81478644d26a47ebc
10 changes: 6 additions & 4 deletions babel/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,10 +384,12 @@ def __eq__(self, other: object) -> bool:
for key in ('language', 'territory', 'script', 'variant'):
if not hasattr(other, key):
return False
return (self.language == getattr(other, 'language')) and \
(self.territory == getattr(other, 'territory')) and \
(self.script == getattr(other, 'script')) and \
(self.variant == getattr(other, 'variant'))
return (
(self.language == getattr(other, 'language')) and # noqa: B009
(self.territory == getattr(other, 'territory')) and # noqa: B009
(self.script == getattr(other, 'script')) and # noqa: B009
(self.variant == getattr(other, 'variant')) # noqa: B009
)

def __ne__(self, other: object) -> bool:
return not self.__eq__(other)
Expand Down
6 changes: 3 additions & 3 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,13 @@ def get_timezone(zone: str | tzinfo | None = None) -> tzinfo:
if pytz:
try:
return pytz.timezone(zone)
except pytz.UnknownTimeZoneError as exc:
except pytz.UnknownTimeZoneError as exc: # noqa: F841
pass
else:
assert zoneinfo
try:
return zoneinfo.ZoneInfo(zone)
except zoneinfo.ZoneInfoNotFoundError as exc:
except zoneinfo.ZoneInfoNotFoundError as exc: # noqa: F841
pass

raise LookupError(f"Unknown timezone {zone}") from exc
Expand Down Expand Up @@ -1814,7 +1814,7 @@ def append_field():
fieldchar[0] = ''
fieldnum[0] = 0

for idx, char in enumerate(pattern.replace("''", '\0')):
for char in pattern.replace("''", '\0'):
if quotebuf is None:
if char == "'": # quote started
if fieldchar[0]:
Expand Down
2 changes: 1 addition & 1 deletion babel/messages/checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def _compatible(a: str, b: str) -> bool:

def _check_positional(results: list[tuple[str, str]]) -> bool:
positional = None
for name, char in results:
for name, _char in results:
if positional is None:
positional = name is None
else:
Expand Down
5 changes: 3 additions & 2 deletions babel/messages/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from configparser import RawConfigParser
from datetime import datetime
from io import StringIO
from typing import Iterable

from babel import __version__ as VERSION
from babel import Locale, localedata
Expand Down Expand Up @@ -187,7 +188,7 @@ def finalize_options(self):
def run(self):
n_errors = 0
for domain in self.domain:
for catalog, errors in self._run_domain(domain).items():
for errors in self._run_domain(domain).values():
n_errors += len(errors)
if n_errors:
self.log.error('%d errors encountered.', n_errors)
Expand Down Expand Up @@ -1104,7 +1105,7 @@ def parse_mapping(fileobj, filename=None):
return method_map, options_map


def parse_keywords(strings=[]):
def parse_keywords(strings: Iterable[str] = ()):
"""Parse keywords specifications from the given list of strings.

>>> kw = sorted(parse_keywords(['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2']).items())
Expand Down
2 changes: 1 addition & 1 deletion babel/messages/jslexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def tokenize(source: str, jsx: bool = True, dotted: bool = True, template_string

while pos < end:
# handle regular rules first
for token_type, rule in rules:
for token_type, rule in rules: # noqa: B007
match = rule.match(source, pos)
if match is not None:
break
Expand Down
5 changes: 2 additions & 3 deletions babel/messages/mofile.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ def read_mo(fileobj: SupportsRead[bytes]) -> Catalog:
else:
raise OSError(0, 'Bad magic number', filename)

# Now put all messages from the .mo file buffer into the catalog
# dictionary
for i in range(0, msgcount):
# Now put all messages from the .mo file buffer into the catalog dictionary
for _i in range(msgcount):
mlen, moff = unpack(ii, buf[origidx:origidx + 8])
mend = moff + mlen
tlen, toff = unpack(ii, buf[transidx:transidx + 8])
Expand Down
6 changes: 3 additions & 3 deletions babel/messages/pofile.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,10 +450,10 @@ def normalize(string: str, prefix: str = '', width: int = 76) -> str:
buf = []
size = 2
while chunks:
l = len(escape(chunks[-1])) - 2 + prefixlen
if size + l < width:
length = len(escape(chunks[-1])) - 2 + prefixlen
if size + length < width:
buf.append(chunks.pop())
size += l
size += length
else:
if not buf:
# handle long chunks by putting them on a
Expand Down
2 changes: 1 addition & 1 deletion babel/plural.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ def value(self):

def _binary_compiler(tmpl):
"""Compiler factory for the `_Compiler`."""
return lambda self, l, r: tmpl % (self.compile(l), self.compile(r))
return lambda self, left, right: tmpl % (self.compile(left), self.compile(right))


def _unary_compiler(tmpl):
Expand Down
6 changes: 3 additions & 3 deletions babel/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,16 +336,16 @@ def __copy__(self) -> LazyProxy:
return LazyProxy(
self._func,
enable_cache=self._is_cache_enabled,
*self._args,
**self._kwargs
*self._args, # noqa: B026
**self._kwargs,
)

def __deepcopy__(self, memo: Any) -> LazyProxy:
from copy import deepcopy
return LazyProxy(
deepcopy(self._func, memo),
enable_cache=deepcopy(self._is_cache_enabled, memo),
*deepcopy(self._args, memo),
*deepcopy(self._args, memo), # noqa: B026
**deepcopy(self._kwargs, memo)
)

Expand Down
8 changes: 4 additions & 4 deletions scripts/import_cldr.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@
BABEL_PACKAGE_ROOT = os.path.join(CHECKOUT_ROOT, "babel")
sys.path.insert(0, CHECKOUT_ROOT)

from babel import dates, numbers
from babel.dates import split_interval_pattern
from babel.localedata import Alias
from babel.plural import PluralRule
from babel import dates, numbers # noqa: E402
from babel.dates import split_interval_pattern # noqa: E402
from babel.localedata import Alias # noqa: E402
from babel.plural import PluralRule # noqa: E402

parse = ElementTree.parse
weekdays = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5,
Expand Down
54 changes: 27 additions & 27 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,36 +97,36 @@ def test_negotiate_custom_separator(self):
assert (de_DE.language, de_DE.territory) == ('de', 'DE')

def test_parse(self):
l = Locale.parse('de-DE', sep='-')
assert l.display_name == 'Deutsch (Deutschland)'
locale = Locale.parse('de-DE', sep='-')
assert locale.display_name == 'Deutsch (Deutschland)'

de_DE = Locale.parse(l)
de_DE = Locale.parse(locale)
assert (de_DE.language, de_DE.territory) == ('de', 'DE')

def test_parse_likely_subtags(self):
l = Locale.parse('zh-TW', sep='-')
assert l.language == 'zh'
assert l.territory == 'TW'
assert l.script == 'Hant'

l = Locale.parse('zh_CN')
assert l.language == 'zh'
assert l.territory == 'CN'
assert l.script == 'Hans'

l = Locale.parse('zh_SG')
assert l.language == 'zh'
assert l.territory == 'SG'
assert l.script == 'Hans'

l = Locale.parse('und_AT')
assert l.language == 'de'
assert l.territory == 'AT'

l = Locale.parse('und_UK')
assert l.language == 'en'
assert l.territory == 'GB'
assert l.script is None
locale = Locale.parse('zh-TW', sep='-')
assert locale.language == 'zh'
assert locale.territory == 'TW'
assert locale.script == 'Hant'

locale = Locale.parse('zh_CN')
assert locale.language == 'zh'
assert locale.territory == 'CN'
assert locale.script == 'Hans'

locale = Locale.parse('zh_SG')
assert locale.language == 'zh'
assert locale.territory == 'SG'
assert locale.script == 'Hans'

locale = Locale.parse('und_AT')
assert locale.language == 'de'
assert locale.territory == 'AT'

locale = Locale.parse('und_UK')
assert locale.language == 'en'
assert locale.territory == 'GB'
assert locale.script is None

def test_get_display_name(self):
zh_CN = Locale('zh', 'CN', script='Hans')
Expand Down Expand Up @@ -322,7 +322,7 @@ def test_issue_601_no_language_name_but_has_variant():
# Instead, it's better to return None altogether, as we can't reliably format
# part of a language name.

assert Locale.parse('fi_FI').get_display_name('kw_GB') == None
assert Locale.parse('fi_FI').get_display_name('kw_GB') is None


def test_issue_814():
Expand Down
23 changes: 11 additions & 12 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,17 +216,17 @@ def test_timezone_walltime_long(self, timezone_getter):
assert dates.DateTimeFormat(t, locale='fr_FR')['vvvv'] == 'heure d’Europe centrale'

def test_hour_formatting(self):
l = 'en_US'
locale = 'en_US'
t = time(0, 0, 0)
assert dates.format_time(t, 'h a', locale=l) == '12 AM'
assert dates.format_time(t, 'H', locale=l) == '0'
assert dates.format_time(t, 'k', locale=l) == '24'
assert dates.format_time(t, 'K a', locale=l) == '0 AM'
assert dates.format_time(t, 'h a', locale=locale) == '12 AM'
assert dates.format_time(t, 'H', locale=locale) == '0'
assert dates.format_time(t, 'k', locale=locale) == '24'
assert dates.format_time(t, 'K a', locale=locale) == '0 AM'
t = time(12, 0, 0)
assert dates.format_time(t, 'h a', locale=l) == '12 PM'
assert dates.format_time(t, 'H', locale=l) == '12'
assert dates.format_time(t, 'k', locale=l) == '12'
assert dates.format_time(t, 'K a', locale=l) == '0 PM'
assert dates.format_time(t, 'h a', locale=locale) == '12 PM'
assert dates.format_time(t, 'H', locale=locale) == '12'
assert dates.format_time(t, 'k', locale=locale) == '12'
assert dates.format_time(t, 'K a', locale=locale) == '0 PM'


class FormatDateTestCase:
Expand Down Expand Up @@ -323,7 +323,6 @@ def test_timezone_formats_kolkata(self, timezone_getter):
assert dates.format_datetime(dt, 'xxxxx', locale='en') == '+05:30'



class FormatTimeTestCase:

def test_with_naive_datetime_and_tzinfo(self, timezone_getter):
Expand Down Expand Up @@ -449,7 +448,7 @@ def test_get_timezone_gmt(timezone_getter):
dt = datetime(2007, 4, 1, 15, 30)
assert dates.get_timezone_gmt(dt, locale='en') == 'GMT+00:00'
assert dates.get_timezone_gmt(dt, locale='en', return_z=True) == 'Z'
assert dates.get_timezone_gmt(dt, locale='en', width='iso8601_short') == u'+00'
assert dates.get_timezone_gmt(dt, locale='en', width='iso8601_short') == '+00'
tz = timezone_getter('America/Los_Angeles')
dt = _localize(tz, datetime(2007, 4, 1, 15, 30))
assert dates.get_timezone_gmt(dt, locale='en') == 'GMT-07:00'
Expand Down Expand Up @@ -581,7 +580,7 @@ def test_format_datetime(timezone_getter):
tzinfo=timezone_getter('US/Eastern'),
locale='en'
)
assert custom == u'2007.04.01 AD at 11:30:00 EDT'
assert custom == '2007.04.01 AD at 11:30:00 EDT'


def test_format_time(timezone_getter):
Expand Down
16 changes: 7 additions & 9 deletions tests/test_localedata.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ def test_merge():


def test_locale_identification():
for l in localedata.locale_identifiers():
assert localedata.exists(l)
for locale in localedata.locale_identifiers():
assert localedata.exists(locale)


def test_unique_ids():
Expand All @@ -84,24 +84,22 @@ def test_unique_ids():


def test_mixedcased_locale():
for l in localedata.locale_identifiers():
for locale in localedata.locale_identifiers():
locale_id = ''.join([
methodcaller(random.choice(['lower', 'upper']))(c) for c in l])
methodcaller(random.choice(['lower', 'upper']))(c) for c in locale])
assert localedata.exists(locale_id)


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 == 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 == False
assert not localedata.exists(['en_us', None])


def test_locale_identifiers_cache(monkeypatch):
Expand Down
16 changes: 8 additions & 8 deletions tests/test_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,14 +226,14 @@ def test_validate_currency():

def test_is_currency():
assert is_currency('EUR')
assert is_currency('eUr') == False
assert is_currency('FUU') == False
assert is_currency('') == False
assert is_currency(None) == False
assert is_currency(' EUR ') == False
assert is_currency(' ') == False
assert is_currency([]) == False
assert is_currency(set()) == False
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():
Expand Down