From 5054afdc86d35c25ae91688b5258440aa44a2e4f Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Wed, 25 Jan 2023 21:51:37 +0200 Subject: [PATCH] Apply some simplification fixes courtesy of Ruff --- babel/core.py | 14 +++++------ babel/dates.py | 49 +++++++++++++----------------------- babel/localedata.py | 5 +--- babel/localtime/_fallback.py | 5 +--- babel/messages/extract.py | 10 ++------ babel/messages/frontend.py | 5 +--- babel/messages/pofile.py | 10 ++------ babel/numbers.py | 11 +++----- babel/plural.py | 2 +- babel/support.py | 5 +--- 10 files changed, 36 insertions(+), 80 deletions(-) diff --git a/babel/core.py b/babel/core.py index 7d3191002..6b0c45d77 100644 --- a/babel/core.py +++ b/babel/core.py @@ -1175,9 +1175,8 @@ def parse_locale(identifier: str, sep: str = '_') -> tuple[str, str | None, str raise ValueError(f"expected only letters, got {lang!r}") script = territory = variant = None - if parts: - if len(parts[0]) == 4 and parts[0].isalpha(): - script = parts.pop(0).title() + if parts and len(parts[0]) == 4 and parts[0].isalpha(): + script = parts.pop(0).title() if parts: if len(parts[0]) == 2 and parts[0].isalpha(): @@ -1185,10 +1184,11 @@ def parse_locale(identifier: str, sep: str = '_') -> tuple[str, str | None, str elif len(parts[0]) == 3 and parts[0].isdigit(): territory = parts.pop(0) - if parts: - if len(parts[0]) == 4 and parts[0][0].isdigit() or \ - len(parts[0]) >= 5 and parts[0][0].isalpha(): - variant = parts.pop().upper() + if parts and ( + len(parts[0]) == 4 and parts[0][0].isdigit() or + len(parts[0]) >= 5 and parts[0][0].isalpha() + ): + variant = parts.pop().upper() if parts: raise ValueError(f"{identifier!r} is not a valid locale identifier") diff --git a/babel/dates.py b/babel/dates.py index 83ce72862..2e3b2e11c 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -93,10 +93,7 @@ def _get_dt_and_tzinfo(dt_or_tzinfo: _DtOrTzinfo) -> tuple[datetime.datetime | N tzinfo = UTC elif isinstance(dt_or_tzinfo, (datetime.datetime, datetime.time)): dt = _get_datetime(dt_or_tzinfo) - if dt.tzinfo is not None: - tzinfo = dt.tzinfo - else: - tzinfo = UTC + tzinfo = dt.tzinfo if dt.tzinfo is not None else UTC else: dt = None tzinfo = dt_or_tzinfo @@ -151,7 +148,7 @@ def _get_datetime(instant: _Instant) -> datetime.datetime: """ if instant is None: return datetime.datetime.utcnow() - elif isinstance(instant, int) or isinstance(instant, float): + elif isinstance(instant, (int, float)): return datetime.datetime.utcfromtimestamp(instant) elif isinstance(instant, datetime.time): return datetime.datetime.combine(datetime.date.today(), instant) @@ -732,10 +729,7 @@ def get_timezone_name( zone_variant = 'generic' else: dst = tzinfo.dst(dt) - if dst: - zone_variant = 'daylight' - else: - zone_variant = 'standard' + zone_variant = "daylight" if dst else "standard" else: if zone_variant not in ('generic', 'standard', 'daylight'): raise ValueError('Invalid zone variation') @@ -746,9 +740,8 @@ def get_timezone_name( return zone info = locale.time_zones.get(zone, {}) # Try explicitly translated zone names first - if width in info: - if zone_variant in info[width]: - return info[width][zone_variant] + if width in info and zone_variant in info[width]: + return info[width][zone_variant] metazone = get_global('meta_zones').get(zone) if metazone: @@ -1205,15 +1198,14 @@ def format_interval( # > single date using availableFormats, and return. for field in PATTERN_CHAR_ORDER: # These are in largest-to-smallest order - if field in skel_formats: - if start_fmt.extract(field) != end_fmt.extract(field): - # > If there is a match, use the pieces of the corresponding pattern to - # > format the start and end datetime, as above. - return "".join( - parse_pattern(pattern).apply(instant, locale) - for pattern, instant - in zip(skel_formats[field], (start, end)) - ) + if field in skel_formats and start_fmt.extract(field) != end_fmt.extract(field): + # > If there is a match, use the pieces of the corresponding pattern to + # > format the start and end datetime, as above. + return "".join( + parse_pattern(pattern).apply(instant, locale) + for pattern, instant + in zip(skel_formats[field], (start, end)) + ) # > Otherwise, format the start and end datetime using the fallback pattern. @@ -1352,10 +1344,7 @@ def parse_date( # names, both in the requested locale, and english year = numbers[indexes['Y']] - if len(year) == 2: - year = 2000 + int(year) - else: - year = int(year) + year = 2000 + int(year) if len(year) == 2 else int(year) month = int(numbers[indexes['M']]) day = int(numbers[indexes['D']]) if month > 12: @@ -1402,9 +1391,8 @@ def parse_time( # Check if the format specifies a period to be used; # if it does, look for 'pm' to figure out an offset. hour_offset = 0 - if 'a' in format_str: - if 'pm' in string.lower(): - hour_offset = 12 + if 'a' in format_str and 'pm' in string.lower(): + hour_offset = 12 # Parse up to three numbers from the string. minute = second = 0 @@ -1607,10 +1595,7 @@ def format_weekday(self, char: str = 'E', num: int = 4) -> str: num = 3 weekday = self.value.weekday() width = {3: 'abbreviated', 4: 'wide', 5: 'narrow', 6: 'short'}[num] - if char == 'c': - context = 'stand-alone' - else: - context = 'format' + context = "stand-alone" if char == "c" else "format" return get_day_names(width, context, self.locale)[weekday] def format_day_of_year(self, num: int) -> str: diff --git a/babel/localedata.py b/babel/localedata.py index c14391aa7..f765a1ea3 100644 --- a/babel/localedata.py +++ b/babel/localedata.py @@ -136,10 +136,7 @@ def load(name: os.PathLike[str] | str, merge_inherited: bool = True) -> dict[str parent = get_global('parent_exceptions').get(name) if not parent: parts = name.split('_') - if len(parts) == 1: - parent = 'root' - else: - parent = '_'.join(parts[:-1]) + parent = "root" if len(parts) == 1 else "_".join(parts[:-1]) data = load(parent).copy() filename = resolve_locale_filename(name) with open(filename, 'rb') as fileobj: diff --git a/babel/localtime/_fallback.py b/babel/localtime/_fallback.py index 836f5962c..14979a53b 100644 --- a/babel/localtime/_fallback.py +++ b/babel/localtime/_fallback.py @@ -12,10 +12,7 @@ import time STDOFFSET = datetime.timedelta(seconds=-time.timezone) -if time.daylight: - DSTOFFSET = datetime.timedelta(seconds=-time.altzone) -else: - DSTOFFSET = STDOFFSET +DSTOFFSET = datetime.timedelta(seconds=-time.altzone) if time.daylight else STDOFFSET DSTDIFF = DSTOFFSET - STDOFFSET ZERO = datetime.timedelta(0) diff --git a/babel/messages/extract.py b/babel/messages/extract.py index 453742ed0..39e26a9c7 100644 --- a/babel/messages/extract.py +++ b/babel/messages/extract.py @@ -400,10 +400,7 @@ def extract( options=options or {}) for lineno, funcname, messages, comments in results: - if funcname: - spec = keywords[funcname] or (1,) - else: - spec = (1,) + spec = keywords[funcname] or (1,) if funcname else (1,) if not isinstance(messages, (list, tuple)): messages = [messages] if not messages: @@ -540,10 +537,7 @@ def extract_python( else: messages.append(None) - if len(messages) > 1: - messages = tuple(messages) - else: - messages = messages[0] + messages = tuple(messages) if len(messages) > 1 else messages[0] # Comments don't apply unless they immediately # precede the message if translator_comments and \ diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index ab094ecd4..b10bb6821 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -412,10 +412,7 @@ def finalize_options(self): 'input-dirs and input-paths are mutually exclusive' ) - if self.no_default_keywords: - keywords = {} - else: - keywords = DEFAULT_KEYWORDS.copy() + keywords = {} if self.no_default_keywords else DEFAULT_KEYWORDS.copy() keywords.update(parse_keywords(listify_value(self.keywords))) diff --git a/babel/messages/pofile.py b/babel/messages/pofile.py index aef8cbf7c..73d8cbe61 100644 --- a/babel/messages/pofile.py +++ b/babel/messages/pofile.py @@ -189,10 +189,7 @@ def _add_message(self) -> None: string = tuple(string) else: string = self.translations[0][1].denormalize() - if self.context: - msgctxt = self.context.denormalize() - else: - msgctxt = None + msgctxt = self.context.denormalize() if self.context else None message = Message(msgid, string, list(self.locations), set(self.flags), self.auto_comments, self.user_comments, lineno=self.offset + 1, context=msgctxt) @@ -543,10 +540,7 @@ def _write(text): def _write_comment(comment, prefix=''): # xgettext always wraps comments even if --no-wrap is passed; # provide the same behaviour - if width and width > 0: - _width = width - else: - _width = 76 + _width = width if width and width > 0 else 76 for line in wraptext(comment, _width): _write(f"#{prefix} {line.strip()}\n") diff --git a/babel/numbers.py b/babel/numbers.py index ee9a133b8..59acee212 100644 --- a/babel/numbers.py +++ b/babel/numbers.py @@ -696,10 +696,7 @@ def _format_currency_long_name( # Step 2. # Correct number to numeric type, important for looking up plural rules: - if isinstance(number, str): - number_n = float(number) - else: - number_n = number + number_n = float(number) if isinstance(number, str) else number # Step 3. unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale) @@ -1032,10 +1029,8 @@ def _match_number(pattern): number, exp = number.split('E', 1) else: exp = None - if '@' in number: - if '.' in number and '0' in number: - raise ValueError('Significant digit patterns can not contain ' - '"@" or "0"') + if '@' in number and '.' in number and '0' in number: + raise ValueError('Significant digit patterns can not contain "@" or "0"') if '.' in number: integer, fraction = number.rsplit('.', 1) else: diff --git a/babel/plural.py b/babel/plural.py index 26073ff8f..6cead04e9 100644 --- a/babel/plural.py +++ b/babel/plural.py @@ -334,7 +334,7 @@ class RuleError(Exception): 'f', # visible fraction digits in n, with trailing zeros.* 't', # visible fraction digits in n, without trailing zeros.* 'c', # compact decimal exponent value: exponent of the power of 10 used in compact decimal formatting. - 'e', # currently, synonym for ā€˜cā€™. however, may be redefined in the future. + 'e', # currently, synonym for `c`. however, may be redefined in the future. } _RULES: list[tuple[str | None, re.Pattern[str]]] = [ diff --git a/babel/support.py b/babel/support.py index c1851cf29..59593b86f 100644 --- a/babel/support.py +++ b/babel/support.py @@ -542,10 +542,7 @@ def unpgettext(self, context: str, singular: str, plural: str, num: int) -> str: except KeyError: if self._fallback: return self._fallback.unpgettext(context, singular, plural, num) - if num == 1: - tmsg = str(singular) - else: - tmsg = str(plural) + tmsg = str(singular) if num == 1 else str(plural) return tmsg def dpgettext(self, domain: str, context: str, message: str) -> str | object: