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():
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")
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
"""
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)
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')
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:
# > 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.
# 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:
# 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
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:
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:
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)
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:
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 \
'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)))
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)
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")
# 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)
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:
'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]]] = [
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: