]> git.ipfire.org Git - thirdparty/babel.git/commitdiff
Apply some simplification fixes courtesy of Ruff
authorAarni Koskela <akx@iki.fi>
Wed, 25 Jan 2023 19:51:37 +0000 (21:51 +0200)
committerAarni Koskela <akx@iki.fi>
Wed, 25 Jan 2023 20:34:47 +0000 (22:34 +0200)
babel/core.py
babel/dates.py
babel/localedata.py
babel/localtime/_fallback.py
babel/messages/extract.py
babel/messages/frontend.py
babel/messages/pofile.py
babel/numbers.py
babel/plural.py
babel/support.py

index 7d3191002fd91bf293467a61fe1ca000fa7184c5..6b0c45d771727f17f643d88b075e6139f6cc98da 100644 (file)
@@ -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")
index 0c8abd6cb0635ad67aa2597fcfa468afda216f91..ce439eecda5fc6a5f3c5ee6d9b212c648a65be62 100644 (file)
@@ -92,10 +92,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
@@ -150,7 +147,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)
@@ -615,10 +612,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')
@@ -629,9 +623,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:
@@ -1088,15 +1081,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.
 
@@ -1235,10 +1227,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:
@@ -1285,9 +1274,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
@@ -1490,10 +1478,7 @@ class DateTimeFormat:
             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:
index c14391aa7e7ff11df3eae82ded188532cc0932e2..f765a1ea34b48dda3b04d8a14a034f94b5742a2a 100644 (file)
@@ -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:
index 836f5962c4a2dc025400b24f522573be5b6271d9..14979a53bf1c4549550014d76fdd58930893aced 100644 (file)
@@ -12,10 +12,7 @@ import datetime
 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)
index 453742ed03ac205d1f4c88ffb65b537b713a5e8e..39e26a9c7f3a0acc35e80d415439442cd9d3afa6 100644 (file)
@@ -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 \
index ab094ecd448f77c1488f49620ba0ed7feb7391b9..b10bb6821ec296d222325b25bae115a06d79ebfa 100644 (file)
@@ -412,10 +412,7 @@ class extract_messages(Command):
                     '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)))
 
index aef8cbf7c1991e518ba7d9d3bc8d3359ba546c00..73d8cbe6139dddf9ebea9c2d0c084d8b94cf4bf2 100644 (file)
@@ -189,10 +189,7 @@ class PoFileParser:
             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_po(
     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")
 
index ee9a133b838cc5bc514a57e8fa54ad1021cbf8c9..59acee21229308b646592b44e64f25657a39cc18 100644 (file)
@@ -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 parse_pattern(pattern: NumberPattern | str) -> NumberPattern:
         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:
index 26073ff8f4bb1294034c309c775dbf64529a0d30..6cead04e97d3b9ea719f986dffcb1598f513470c 100644 (file)
@@ -334,7 +334,7 @@ _VARS = {
     '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]]] = [
index c1851cf29592c27961112504e1b42dc72af745f0..59593b86f404e60920f597042042e8e23f11e48a 100644 (file)
@@ -542,10 +542,7 @@ class NullTranslations(gettext.NullTranslations):
         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: