Skip to content

Commit 1af67fe

Browse files
committed
Apply manual formatting/fmt:skip to things that would be poorly autoformatted
1 parent ca6c458 commit 1af67fe

File tree

13 files changed

+104
-98
lines changed

13 files changed

+104
-98
lines changed

babel/core.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def get_global(key: _GLOBAL_KEY) -> Mapping[str, Any]:
119119
'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL',
120120
'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI',
121121
'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA',
122-
}
122+
} # fmt: skip
123123

124124

125125
class UnknownLocaleError(Exception):
@@ -346,7 +346,8 @@ def parse(
346346
f"variables for the API you tried to use."
347347
)
348348
if isinstance(identifier, str):
349-
raise ValueError(msg) # `parse_locale` would raise a ValueError, so let's do that here
349+
# `parse_locale` would raise a ValueError, so let's do that here
350+
raise ValueError(msg)
350351
raise TypeError(msg)
351352

352353
if not isinstance(identifier, str):

babel/dates.py

Lines changed: 37 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
_Instant: TypeAlias = datetime.date | datetime.time | float | None
4242
_PredefinedTimeFormat: TypeAlias = Literal['full', 'long', 'medium', 'short']
4343
_Context: TypeAlias = Literal['format', 'stand-alone']
44-
_DtOrTzinfo: TypeAlias = datetime.datetime | datetime.tzinfo | str | int | datetime.time | None
44+
_DtOrTzinfo: TypeAlias = datetime.datetime | datetime.tzinfo | str | int | datetime.time | None # fmt: skip
4545

4646
# "If a given short metazone form is known NOT to be understood in a given
4747
# locale and the parent locale has this value such that it would normally
@@ -1018,9 +1018,17 @@ def _format_fallback_interval(
10181018
) -> str:
10191019
if skeleton in locale.datetime_skeletons: # Use the given skeleton
10201020
format = lambda dt: format_skeleton(skeleton, dt, tzinfo, locale=locale)
1021-
elif all((isinstance(d, datetime.date) and not isinstance(d, datetime.datetime)) for d in (start, end)): # Both are just dates
1021+
elif all(
1022+
# Both are just dates
1023+
(isinstance(d, datetime.date) and not isinstance(d, datetime.datetime))
1024+
for d in (start, end)
1025+
):
10221026
format = lambda dt: format_date(dt, locale=locale)
1023-
elif all((isinstance(d, datetime.time) and not isinstance(d, datetime.date)) for d in (start, end)): # Both are times
1027+
elif all(
1028+
# Both are times
1029+
(isinstance(d, datetime.time) and not isinstance(d, datetime.date))
1030+
for d in (start, end)
1031+
):
10241032
format = lambda dt: format_time(dt, tzinfo=tzinfo, locale=locale)
10251033
else:
10261034
format = lambda dt: format_datetime(dt, tzinfo=tzinfo, locale=locale)
@@ -1266,8 +1274,11 @@ def parse_date(
12661274
use_predefined_format = format in ('full', 'long', 'medium', 'short')
12671275
# we try ISO-8601 format first, meaning similar to formats
12681276
# extended YYYY-MM-DD or basic YYYYMMDD
1269-
iso_alike = re.match(r'^(\d{4})-?([01]\d)-?([0-3]\d)$',
1270-
string, flags=re.ASCII) # allow only ASCII digits
1277+
iso_alike = re.match(
1278+
r'^(\d{4})-?([01]\d)-?([0-3]\d)$',
1279+
string,
1280+
flags=re.ASCII, # allow only ASCII digits
1281+
)
12711282
if iso_alike and use_predefined_format:
12721283
try:
12731284
return datetime.date(*map(int, iso_alike.groups()))
@@ -1637,35 +1648,24 @@ def format_timezone(self, char: str, num: int) -> str:
16371648
return get_timezone_gmt(value, width, locale=self.locale)
16381649
# TODO: To add support for O:1
16391650
elif char == 'v':
1640-
return get_timezone_name(value.tzinfo, width,
1641-
locale=self.locale)
1651+
return get_timezone_name(value.tzinfo, width, locale=self.locale)
16421652
elif char == 'V':
16431653
if num == 1:
1644-
return get_timezone_name(value.tzinfo, width,
1645-
uncommon=True, locale=self.locale)
1654+
return get_timezone_name(value.tzinfo, width, locale=self.locale)
16461655
elif num == 2:
16471656
return get_timezone_name(value.tzinfo, locale=self.locale, return_zone=True)
16481657
elif num == 3:
1649-
return get_timezone_location(value.tzinfo, locale=self.locale, return_city=True)
1658+
return get_timezone_location(value.tzinfo, locale=self.locale, return_city=True) # fmt: skip
16501659
return get_timezone_location(value.tzinfo, locale=self.locale)
1651-
# Included additional elif condition to add support for 'Xx' in timezone format
1652-
elif char == 'X':
1653-
if num == 1:
1654-
return get_timezone_gmt(value, width='iso8601_short', locale=self.locale,
1655-
return_z=True)
1656-
elif num in (2, 4):
1657-
return get_timezone_gmt(value, width='short', locale=self.locale,
1658-
return_z=True)
1659-
elif num in (3, 5):
1660-
return get_timezone_gmt(value, width='iso8601', locale=self.locale,
1661-
return_z=True)
1662-
elif char == 'x':
1660+
elif char in 'Xx':
1661+
return_z = char == 'X'
16631662
if num == 1:
1664-
return get_timezone_gmt(value, width='iso8601_short', locale=self.locale)
1663+
width = 'iso8601_short'
16651664
elif num in (2, 4):
1666-
return get_timezone_gmt(value, width='short', locale=self.locale)
1665+
width = 'short'
16671666
elif num in (3, 5):
1668-
return get_timezone_gmt(value, width='iso8601', locale=self.locale)
1667+
width = 'iso8601'
1668+
return get_timezone_gmt(value, width=width, locale=self.locale, return_z=return_z) # fmt: skip
16691669

16701670
def format(self, value: SupportsInt, length: int) -> str:
16711671
return '%0*d' % (length, value)
@@ -1739,7 +1739,7 @@ def get_week_number(self, day_of_period: int, day_of_week: int | None = None) ->
17391739
's': [1, 2], 'S': None, 'A': None, # second
17401740
'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4, 5], 'O': [1, 4], 'v': [1, 4], # zone
17411741
'V': [1, 2, 3, 4], 'x': [1, 2, 3, 4, 5], 'X': [1, 2, 3, 4, 5], # zone
1742-
}
1742+
} # fmt: skip
17431743

17441744
#: The pattern characters declared in the Date Field Symbol Table
17451745
#: (https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table)
@@ -1967,11 +1967,11 @@ def match_skeleton(skeleton: str, options: Iterable[str], allow_different_fields
19671967
if 'b' in skeleton and not any('b' in option for option in options):
19681968
skeleton = skeleton.replace('b', '')
19691969

1970-
get_input_field_width = dict(t[1] for t in tokenize_pattern(skeleton) if t[0] == "field").get
1970+
get_input_field_width = dict(t[1] for t in tokenize_pattern(skeleton) if t[0] == "field").get # fmt: skip
19711971
best_skeleton = None
19721972
best_distance = None
19731973
for option in options:
1974-
get_opt_field_width = dict(t[1] for t in tokenize_pattern(option) if t[0] == "field").get
1974+
get_opt_field_width = dict(t[1] for t in tokenize_pattern(option) if t[0] == "field").get # fmt: skip
19751975
distance = 0
19761976
for field in PATTERN_CHARS:
19771977
input_width = get_input_field_width(field, 0)
@@ -1982,13 +1982,18 @@ def match_skeleton(skeleton: str, options: Iterable[str], allow_different_fields
19821982
if not allow_different_fields: # This one is not okay
19831983
option = None
19841984
break
1985-
distance += 0x1000 # Magic weight constant for "entirely different fields"
1986-
elif field == 'M' and ((input_width > 2 and opt_width <= 2) or (input_width <= 2 and opt_width > 2)):
1987-
distance += 0x100 # Magic weight for "text turns into a number"
1985+
# Magic weight constant for "entirely different fields"
1986+
distance += 0x1000
1987+
elif field == 'M' and (
1988+
(input_width > 2 and opt_width <= 2) or (input_width <= 2 and opt_width > 2)
1989+
):
1990+
# Magic weight constant for "text turns into a number"
1991+
distance += 0x100
19881992
else:
19891993
distance += abs(input_width - opt_width)
19901994

1991-
if not option: # We lost the option along the way (probably due to "allow_different_fields")
1995+
if not option:
1996+
# We lost the option along the way (probably due to "allow_different_fields")
19921997
continue
19931998

19941999
if not best_skeleton or distance < best_distance:

babel/localtime/_fallback.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def tzname(self, dt: datetime.datetime) -> str:
3838
def _isdst(self, dt: datetime.datetime) -> bool:
3939
tt = (dt.year, dt.month, dt.day,
4040
dt.hour, dt.minute, dt.second,
41-
dt.weekday(), 0, -1)
41+
dt.weekday(), 0, -1) # fmt: skip
4242
stamp = time.mktime(tt)
4343
tt = time.localtime(stamp)
4444
return tt.tm_isdst > 0

babel/messages/catalog.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ def _get_mime_headers(self) -> list[tuple[str, str]]:
504504
('POT-Creation-Date', format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ', locale='en')),
505505
('PO-Revision-Date', revision_date),
506506
('Last-Translator', self.last_translator),
507-
]
507+
] # fmt: skip
508508
if self.locale_identifier:
509509
headers.append(('Language', str(self.locale_identifier)))
510510
headers.append(('Language-Team', language_team))

babel/messages/extract.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def tell(self) -> int: ...
6262
_Keyword: TypeAlias = dict[int | None, _SimpleKeyword] | _SimpleKeyword
6363

6464
# 5-tuple of (filename, lineno, messages, comments, context)
65-
_FileExtractionResult: TypeAlias = tuple[str, int, str | tuple[str, ...], list[str], str | None]
65+
_FileExtractionResult: TypeAlias = tuple[str, int, str | tuple[str, ...], list[str], str | None] # fmt: skip
6666

6767
# 4-tuple of (lineno, message, comments, context)
6868
_ExtractionResult: TypeAlias = tuple[int, str | tuple[str, ...], list[str], str | None]
@@ -72,7 +72,7 @@ def tell(self) -> int: ...
7272
_CallableExtractionMethod: TypeAlias = Callable[
7373
[_FileObj | IO[bytes], Mapping[str, _Keyword], Collection[str], Mapping[str, Any]],
7474
Iterable[_ExtractionResult],
75-
]
75+
] # fmt: skip
7676

7777
_ExtractionMethod: TypeAlias = _CallableExtractionMethod | str
7878

@@ -696,9 +696,12 @@ def extract_javascript(
696696
lineno=lineno,
697697
):
698698
if ( # Turn keyword`foo` expressions into keyword("foo") calls:
699-
funcname and # have a keyword...
700-
(last_token and last_token.type == 'name') and # we've seen nothing after the keyword...
701-
token.type == 'template_string' # this is a template string
699+
# have a keyword...
700+
funcname
701+
# and we've seen nothing after the keyword...
702+
and (last_token and last_token.type == 'name')
703+
# and this is a template string
704+
and token.type == 'template_string'
702705
):
703706
message_lineno = token.lineno
704707
messages = [unquote_string(token.value)]

babel/messages/frontend.py

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ class CompileCatalog(CommandMixin):
173173
'also include fuzzy translations'),
174174
('statistics', None,
175175
'print statistics about translations'),
176-
]
176+
] # fmt: skip
177177
boolean_options = ['use-fuzzy', 'statistics']
178178

179179
def initialize_options(self):
@@ -207,30 +207,23 @@ def _run_domain(self, domain):
207207

208208
if not self.input_file:
209209
if self.locale:
210-
po_files.append((self.locale,
211-
os.path.join(self.directory, self.locale,
212-
'LC_MESSAGES',
213-
f"{domain}.po")))
214-
mo_files.append(os.path.join(self.directory, self.locale,
215-
'LC_MESSAGES',
216-
f"{domain}.mo"))
210+
lc_messages_path = os.path.join(self.directory, self.locale, 'LC_MESSAGES')
211+
po_files.append((self.locale, os.path.join(lc_messages_path, f"{domain}.po")))
212+
mo_files.append(os.path.join(lc_messages_path, f"{domain}.mo"))
217213
else:
218214
for locale in os.listdir(self.directory):
219-
po_file = os.path.join(self.directory, locale,
220-
'LC_MESSAGES', f"{domain}.po")
215+
lc_messages_path = os.path.join(self.directory, locale, 'LC_MESSAGES')
216+
po_file = os.path.join(lc_messages_path, f"{domain}.po")
221217
if os.path.exists(po_file):
222218
po_files.append((locale, po_file))
223-
mo_files.append(os.path.join(self.directory, locale,
224-
'LC_MESSAGES',
225-
f"{domain}.mo"))
219+
mo_files.append(os.path.join(lc_messages_path, f"{domain}.mo"))
226220
else:
227221
po_files.append((self.locale, self.input_file))
228222
if self.output_file:
229223
mo_files.append(self.output_file)
230224
else:
231-
mo_files.append(os.path.join(self.directory, self.locale,
232-
'LC_MESSAGES',
233-
f"{domain}.mo"))
225+
lc_messages_path = os.path.join(self.directory, self.locale, 'LC_MESSAGES')
226+
mo_files.append(os.path.join(lc_messages_path, f"{domain}.mo"))
234227

235228
if not po_files:
236229
raise OptionError('no message catalogs found')
@@ -347,7 +340,7 @@ class ExtractMessages(CommandMixin):
347340
'header comment for the catalog'),
348341
('last-translator=', None,
349342
'set the name and email of the last translator in output'),
350-
]
343+
] # fmt: skip
351344
boolean_options = [
352345
'no-default-keywords', 'no-location', 'omit-header', 'no-wrap',
353346
'sort-output', 'sort-by-file', 'strip-comments',
@@ -596,7 +589,7 @@ class InitCatalog(CommandMixin):
596589
('no-wrap', None,
597590
'do not break long message lines, longer than the output line width, '
598591
'into several lines'),
599-
]
592+
] # fmt: skip
600593
boolean_options = ['no-wrap']
601594

602595
def initialize_options(self):
@@ -689,7 +682,7 @@ class UpdateCatalog(CommandMixin):
689682
'would be updated'),
690683
('ignore-pot-creation-date=', None,
691684
'ignore changes to POT-Creation-Date when updating or checking'),
692-
]
685+
] # fmt: skip
693686
boolean_options = [
694687
'omit-header', 'no-wrap', 'ignore-obsolete', 'init-missing',
695688
'no-fuzzy-matching', 'previous', 'update-header-comment',

babel/messages/jslexer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
'+=', '-=', '*=', '%=', '<<', '>>', '>>>', '<<=', '>>=',
2020
'>>>=', '&', '&=', '|', '|=', '&&', '||', '^', '^=', '(', ')',
2121
'[', ']', '{', '}', '!', '--', '++', '~', ',', ';', '.', ':',
22-
], key=len, reverse=True)
22+
], key=len, reverse=True) # fmt: skip
2323

2424
escapes: dict[str, str] = {'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t'}
2525

@@ -59,7 +59,7 @@ class Token(NamedTuple):
5959
'(?:[^'\\]*(?:\\.[^'\\]*)*)' |
6060
"(?:[^"\\]*(?:\\.[^"\\]*)*)"
6161
)''', re.VERBOSE | re.DOTALL)),
62-
]
62+
] # fmt: skip
6363

6464

6565
def get_rules(jsx: bool, dotted: bool, template_string: bool) -> list[tuple[str | None, re.Pattern[str]]]:

babel/messages/mofile.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -164,24 +164,19 @@ def write_mo(fileobj: SupportsWrite[bytes], catalog: Catalog, use_fuzzy: bool =
164164
# For each string, we need size and file offset. Each string is NUL
165165
# terminated; the NUL does not count into the size.
166166
if message.pluralizable:
167-
msgid = b'\x00'.join([
168-
msgid.encode(catalog.charset) for msgid in message.id
169-
])
167+
msgid = b'\x00'.join(msgid.encode(catalog.charset) for msgid in message.id)
170168
msgstrs = []
171169
for idx, string in enumerate(message.string):
172170
if not string:
173171
msgstrs.append(message.id[min(int(idx), 1)])
174172
else:
175173
msgstrs.append(string)
176-
msgstr = b'\x00'.join([
177-
msgstr.encode(catalog.charset) for msgstr in msgstrs
178-
])
174+
msgstr = b'\x00'.join(msgstr.encode(catalog.charset) for msgstr in msgstrs)
179175
else:
180176
msgid = message.id.encode(catalog.charset)
181177
msgstr = message.string.encode(catalog.charset)
182178
if message.context:
183-
msgid = b'\x04'.join([message.context.encode(catalog.charset),
184-
msgid])
179+
msgid = b'\x04'.join([message.context.encode(catalog.charset), msgid])
185180
offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
186181
ids += msgid + b'\x00'
187182
strs += msgstr + b'\x00'
@@ -200,11 +195,15 @@ def write_mo(fileobj: SupportsWrite[bytes], catalog: Catalog, use_fuzzy: bool =
200195
voffsets += [l2, o2 + valuestart]
201196
offsets = koffsets + voffsets
202197

203-
fileobj.write(struct.pack('Iiiiiii',
204-
LE_MAGIC, # magic
205-
0, # version
206-
len(messages), # number of entries
207-
7 * 4, # start of key index
208-
7 * 4 + len(messages) * 8, # start of value index
209-
0, 0, # size and offset of hash table
210-
) + array.array.tobytes(array.array("i", offsets)) + ids + strs)
198+
header = struct.pack(
199+
'Iiiiiii',
200+
LE_MAGIC, # magic
201+
0, # version
202+
len(messages), # number of entries
203+
7 * 4, # start of key index
204+
7 * 4 + len(messages) * 8, # start of value index
205+
0,
206+
0, # size and offset of hash table
207+
)
208+
209+
fileobj.write(header + array.array.tobytes(array.array("i", offsets)) + ids + strs)

babel/messages/plurals.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@
197197
'xh': (2, '(n != 1)'),
198198
# Chinese - From Pootle's PO's (modified)
199199
'zh': (1, '0'),
200-
}
200+
} # fmt: skip
201201

202202

203203
DEFAULT_PLURAL: tuple[int, str] = (2, '(n != 1)')

babel/numbers.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -432,7 +432,7 @@ def get_exponential_symbol(
432432
:raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
433433
"""
434434
locale = Locale.parse(locale or LC_NUMERIC)
435-
return _get_number_symbols(locale, numbering_system=numbering_system).get('exponential', 'E')
435+
return _get_number_symbols(locale, numbering_system=numbering_system).get('exponential', 'E') # fmt: skip
436436

437437

438438
def get_group_symbol(
@@ -1054,9 +1054,12 @@ def parse_number(
10541054
group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
10551055

10561056
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,
1057+
# if the grouping symbol is a kind of space,
1058+
group_symbol in SPACE_CHARS
1059+
# and the string to be parsed does not contain it,
1060+
and group_symbol not in string
1061+
# but it does contain any other kind of space instead,
1062+
and SPACE_CHARS_RE.search(string)
10601063
):
10611064
# ... it's reasonable to assume it is taking the place of the grouping symbol.
10621065
string = SPACE_CHARS_RE.sub(group_symbol, string)
@@ -1120,9 +1123,10 @@ def parse_decimal(
11201123
decimal_symbol = get_decimal_symbol(locale, numbering_system=numbering_system)
11211124

11221125
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+
group_symbol in SPACE_CHARS # if the grouping symbol is a kind of space,
1127+
and group_symbol not in string # and the string to be parsed does not contain it,
1128+
# but it does contain any other kind of space instead,
1129+
and SPACE_CHARS_RE.search(string)
11261130
):
11271131
# ... it's reasonable to assume it is taking the place of the grouping symbol.
11281132
string = SPACE_CHARS_RE.sub(group_symbol, string)

0 commit comments

Comments
 (0)