Skip to content

Commit 28ea5fe

Browse files
committed
Apply some simplification fixes courtesy of Ruff
1 parent b3d3381 commit 28ea5fe

10 files changed

Lines changed: 36 additions & 80 deletions

File tree

babel/core.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1175,20 +1175,20 @@ def parse_locale(identifier: str, sep: str = '_') -> tuple[str, str | None, str
11751175
raise ValueError(f"expected only letters, got {lang!r}")
11761176

11771177
script = territory = variant = None
1178-
if parts:
1179-
if len(parts[0]) == 4 and parts[0].isalpha():
1180-
script = parts.pop(0).title()
1178+
if parts and len(parts[0]) == 4 and parts[0].isalpha():
1179+
script = parts.pop(0).title()
11811180

11821181
if parts:
11831182
if len(parts[0]) == 2 and parts[0].isalpha():
11841183
territory = parts.pop(0).upper()
11851184
elif len(parts[0]) == 3 and parts[0].isdigit():
11861185
territory = parts.pop(0)
11871186

1188-
if parts:
1189-
if len(parts[0]) == 4 and parts[0][0].isdigit() or \
1190-
len(parts[0]) >= 5 and parts[0][0].isalpha():
1191-
variant = parts.pop().upper()
1187+
if parts and (
1188+
len(parts[0]) == 4 and parts[0][0].isdigit() or
1189+
len(parts[0]) >= 5 and parts[0][0].isalpha()
1190+
):
1191+
variant = parts.pop().upper()
11921192

11931193
if parts:
11941194
raise ValueError(f"{identifier!r} is not a valid locale identifier")

babel/dates.py

Lines changed: 17 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,7 @@ def _get_dt_and_tzinfo(dt_or_tzinfo: _DtOrTzinfo) -> tuple[datetime.datetime | N
9292
tzinfo = UTC
9393
elif isinstance(dt_or_tzinfo, (datetime.datetime, datetime.time)):
9494
dt = _get_datetime(dt_or_tzinfo)
95-
if dt.tzinfo is not None:
96-
tzinfo = dt.tzinfo
97-
else:
98-
tzinfo = UTC
95+
tzinfo = dt.tzinfo if dt.tzinfo is not None else UTC
9996
else:
10097
dt = None
10198
tzinfo = dt_or_tzinfo
@@ -150,7 +147,7 @@ def _get_datetime(instant: _Instant) -> datetime.datetime:
150147
"""
151148
if instant is None:
152149
return datetime.datetime.utcnow()
153-
elif isinstance(instant, int) or isinstance(instant, float):
150+
elif isinstance(instant, (int, float)):
154151
return datetime.datetime.utcfromtimestamp(instant)
155152
elif isinstance(instant, datetime.time):
156153
return datetime.datetime.combine(datetime.date.today(), instant)
@@ -615,10 +612,7 @@ def get_timezone_name(
615612
zone_variant = 'generic'
616613
else:
617614
dst = tzinfo.dst(dt)
618-
if dst:
619-
zone_variant = 'daylight'
620-
else:
621-
zone_variant = 'standard'
615+
zone_variant = "daylight" if dst else "standard"
622616
else:
623617
if zone_variant not in ('generic', 'standard', 'daylight'):
624618
raise ValueError('Invalid zone variation')
@@ -629,9 +623,8 @@ def get_timezone_name(
629623
return zone
630624
info = locale.time_zones.get(zone, {})
631625
# Try explicitly translated zone names first
632-
if width in info:
633-
if zone_variant in info[width]:
634-
return info[width][zone_variant]
626+
if width in info and zone_variant in info[width]:
627+
return info[width][zone_variant]
635628

636629
metazone = get_global('meta_zones').get(zone)
637630
if metazone:
@@ -1088,15 +1081,14 @@ def format_interval(
10881081
# > single date using availableFormats, and return.
10891082

10901083
for field in PATTERN_CHAR_ORDER: # These are in largest-to-smallest order
1091-
if field in skel_formats:
1092-
if start_fmt.extract(field) != end_fmt.extract(field):
1093-
# > If there is a match, use the pieces of the corresponding pattern to
1094-
# > format the start and end datetime, as above.
1095-
return "".join(
1096-
parse_pattern(pattern).apply(instant, locale)
1097-
for pattern, instant
1098-
in zip(skel_formats[field], (start, end))
1099-
)
1084+
if field in skel_formats and start_fmt.extract(field) != end_fmt.extract(field):
1085+
# > If there is a match, use the pieces of the corresponding pattern to
1086+
# > format the start and end datetime, as above.
1087+
return "".join(
1088+
parse_pattern(pattern).apply(instant, locale)
1089+
for pattern, instant
1090+
in zip(skel_formats[field], (start, end))
1091+
)
11001092

11011093
# > Otherwise, format the start and end datetime using the fallback pattern.
11021094

@@ -1235,10 +1227,7 @@ def parse_date(
12351227
# names, both in the requested locale, and english
12361228

12371229
year = numbers[indexes['Y']]
1238-
if len(year) == 2:
1239-
year = 2000 + int(year)
1240-
else:
1241-
year = int(year)
1230+
year = 2000 + int(year) if len(year) == 2 else int(year)
12421231
month = int(numbers[indexes['M']])
12431232
day = int(numbers[indexes['D']])
12441233
if month > 12:
@@ -1285,9 +1274,8 @@ def parse_time(
12851274
# Check if the format specifies a period to be used;
12861275
# if it does, look for 'pm' to figure out an offset.
12871276
hour_offset = 0
1288-
if 'a' in format_str:
1289-
if 'pm' in string.lower():
1290-
hour_offset = 12
1277+
if 'a' in format_str and 'pm' in string.lower():
1278+
hour_offset = 12
12911279

12921280
# Parse up to three numbers from the string.
12931281
minute = second = 0
@@ -1490,10 +1478,7 @@ def format_weekday(self, char: str = 'E', num: int = 4) -> str:
14901478
num = 3
14911479
weekday = self.value.weekday()
14921480
width = {3: 'abbreviated', 4: 'wide', 5: 'narrow', 6: 'short'}[num]
1493-
if char == 'c':
1494-
context = 'stand-alone'
1495-
else:
1496-
context = 'format'
1481+
context = "stand-alone" if char == "c" else "format"
14971482
return get_day_names(width, context, self.locale)[weekday]
14981483

14991484
def format_day_of_year(self, num: int) -> str:

babel/localedata.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,10 +136,7 @@ def load(name: os.PathLike[str] | str, merge_inherited: bool = True) -> dict[str
136136
parent = get_global('parent_exceptions').get(name)
137137
if not parent:
138138
parts = name.split('_')
139-
if len(parts) == 1:
140-
parent = 'root'
141-
else:
142-
parent = '_'.join(parts[:-1])
139+
parent = "root" if len(parts) == 1 else "_".join(parts[:-1])
143140
data = load(parent).copy()
144141
filename = resolve_locale_filename(name)
145142
with open(filename, 'rb') as fileobj:

babel/localtime/_fallback.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,7 @@
1212
import time
1313

1414
STDOFFSET = datetime.timedelta(seconds=-time.timezone)
15-
if time.daylight:
16-
DSTOFFSET = datetime.timedelta(seconds=-time.altzone)
17-
else:
18-
DSTOFFSET = STDOFFSET
15+
DSTOFFSET = datetime.timedelta(seconds=-time.altzone) if time.daylight else STDOFFSET
1916

2017
DSTDIFF = DSTOFFSET - STDOFFSET
2118
ZERO = datetime.timedelta(0)

babel/messages/extract.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -400,10 +400,7 @@ def extract(
400400
options=options or {})
401401

402402
for lineno, funcname, messages, comments in results:
403-
if funcname:
404-
spec = keywords[funcname] or (1,)
405-
else:
406-
spec = (1,)
403+
spec = keywords[funcname] or (1,) if funcname else (1,)
407404
if not isinstance(messages, (list, tuple)):
408405
messages = [messages]
409406
if not messages:
@@ -540,10 +537,7 @@ def extract_python(
540537
else:
541538
messages.append(None)
542539

543-
if len(messages) > 1:
544-
messages = tuple(messages)
545-
else:
546-
messages = messages[0]
540+
messages = tuple(messages) if len(messages) > 1 else messages[0]
547541
# Comments don't apply unless they immediately
548542
# precede the message
549543
if translator_comments and \

babel/messages/frontend.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -412,10 +412,7 @@ def finalize_options(self):
412412
'input-dirs and input-paths are mutually exclusive'
413413
)
414414

415-
if self.no_default_keywords:
416-
keywords = {}
417-
else:
418-
keywords = DEFAULT_KEYWORDS.copy()
415+
keywords = {} if self.no_default_keywords else DEFAULT_KEYWORDS.copy()
419416

420417
keywords.update(parse_keywords(listify_value(self.keywords)))
421418

babel/messages/pofile.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,7 @@ def _add_message(self) -> None:
189189
string = tuple(string)
190190
else:
191191
string = self.translations[0][1].denormalize()
192-
if self.context:
193-
msgctxt = self.context.denormalize()
194-
else:
195-
msgctxt = None
192+
msgctxt = self.context.denormalize() if self.context else None
196193
message = Message(msgid, string, list(self.locations), set(self.flags),
197194
self.auto_comments, self.user_comments, lineno=self.offset + 1,
198195
context=msgctxt)
@@ -543,10 +540,7 @@ def _write(text):
543540
def _write_comment(comment, prefix=''):
544541
# xgettext always wraps comments even if --no-wrap is passed;
545542
# provide the same behaviour
546-
if width and width > 0:
547-
_width = width
548-
else:
549-
_width = 76
543+
_width = width if width and width > 0 else 76
550544
for line in wraptext(comment, _width):
551545
_write(f"#{prefix} {line.strip()}\n")
552546

babel/numbers.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -696,10 +696,7 @@ def _format_currency_long_name(
696696
# Step 2.
697697

698698
# Correct number to numeric type, important for looking up plural rules:
699-
if isinstance(number, str):
700-
number_n = float(number)
701-
else:
702-
number_n = number
699+
number_n = float(number) if isinstance(number, str) else number
703700

704701
# Step 3.
705702
unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale)
@@ -1032,10 +1029,8 @@ def _match_number(pattern):
10321029
number, exp = number.split('E', 1)
10331030
else:
10341031
exp = None
1035-
if '@' in number:
1036-
if '.' in number and '0' in number:
1037-
raise ValueError('Significant digit patterns can not contain '
1038-
'"@" or "0"')
1032+
if '@' in number and '.' in number and '0' in number:
1033+
raise ValueError('Significant digit patterns can not contain "@" or "0"')
10391034
if '.' in number:
10401035
integer, fraction = number.rsplit('.', 1)
10411036
else:

babel/plural.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ class RuleError(Exception):
334334
'f', # visible fraction digits in n, with trailing zeros.*
335335
't', # visible fraction digits in n, without trailing zeros.*
336336
'c', # compact decimal exponent value: exponent of the power of 10 used in compact decimal formatting.
337-
'e', # currently, synonym for ‘c’. however, may be redefined in the future.
337+
'e', # currently, synonym for `c`. however, may be redefined in the future.
338338
}
339339

340340
_RULES: list[tuple[str | None, re.Pattern[str]]] = [

babel/support.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -542,10 +542,7 @@ def unpgettext(self, context: str, singular: str, plural: str, num: int) -> str:
542542
except KeyError:
543543
if self._fallback:
544544
return self._fallback.unpgettext(context, singular, plural, num)
545-
if num == 1:
546-
tmsg = str(singular)
547-
else:
548-
tmsg = str(plural)
545+
tmsg = str(singular) if num == 1 else str(plural)
549546
return tmsg
550547

551548
def dpgettext(self, domain: str, context: str, message: str) -> str | object:

0 commit comments

Comments
 (0)