Skip to content

Commit 00e15bb

Browse files
committed
type annotations for units, util
1 parent 483029f commit 00e15bb

2 files changed

Lines changed: 38 additions & 22 deletions

File tree

babel/units.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
1+
from __future__ import annotations
2+
3+
import decimal
4+
5+
from typing_extensions import Literal
6+
17
from babel.core import Locale
2-
from babel.numbers import format_decimal, LC_NUMERIC
8+
from babel.localedata import LocaleDataDict
9+
from babel.numbers import LC_NUMERIC, format_decimal
310

411

512
class UnknownUnitError(ValueError):
6-
def __init__(self, unit, locale):
13+
def __init__(self, unit: str, locale: Locale):
714
ValueError.__init__(self, f"{unit} is not a known unit in {locale}")
815

916

10-
def get_unit_name(measurement_unit, length='long', locale=LC_NUMERIC):
17+
def get_unit_name(measurement_unit: str, length: Literal["short", "long", "narrow"] = 'long',
18+
locale: Locale | str | None = LC_NUMERIC) -> str | None:
1119
"""
1220
Get the display name for a measurement unit in the given locale.
1321
@@ -36,7 +44,7 @@ def get_unit_name(measurement_unit, length='long', locale=LC_NUMERIC):
3644
return locale.unit_display_names.get(unit, {}).get(length)
3745

3846

39-
def _find_unit_pattern(unit_id, locale=LC_NUMERIC):
47+
def _find_unit_pattern(unit_id: str, locale: Locale | str | None = LC_NUMERIC) -> str | None:
4048
"""
4149
Expand an unit into a qualified form.
4250
@@ -62,7 +70,9 @@ def _find_unit_pattern(unit_id, locale=LC_NUMERIC):
6270
return unit_pattern
6371

6472

65-
def format_unit(value, measurement_unit, length='long', format=None, locale=LC_NUMERIC):
73+
def format_unit(value: float | decimal.Decimal, measurement_unit: str,
74+
length: Literal["short", "long", "narrow"] = 'long', format: str | None = None,
75+
locale: Locale | str | None = LC_NUMERIC) -> str:
6676
"""Format a value of a given unit.
6777
6878
Values are formatted according to the locale's usual pluralization rules
@@ -132,7 +142,7 @@ def format_unit(value, measurement_unit, length='long', format=None, locale=LC_N
132142
return f"{formatted_value} {fallback_name or measurement_unit}" # pragma: no cover
133143

134144

135-
def _find_compound_unit(numerator_unit, denominator_unit, locale=LC_NUMERIC):
145+
def _find_compound_unit(numerator_unit: str, denominator_unit: str, locale: Locale | str | None = LC_NUMERIC) -> str | None:
136146
"""
137147
Find a predefined compound unit pattern.
138148
@@ -181,10 +191,10 @@ def _find_compound_unit(numerator_unit, denominator_unit, locale=LC_NUMERIC):
181191

182192

183193
def format_compound_unit(
184-
numerator_value, numerator_unit=None,
185-
denominator_value=1, denominator_unit=None,
186-
length='long', format=None, locale=LC_NUMERIC
187-
):
194+
numerator_value: float | decimal.Decimal, numerator_unit: str | None = None,
195+
denominator_value: float | decimal.Decimal = 1, denominator_unit: str | None = None,
196+
length: Literal["short", "long", "narrow"] = 'long', format: str | None = None,
197+
locale: Locale | str | None = LC_NUMERIC) -> str | None:
188198
"""
189199
Format a compound number value, i.e. "kilometers per hour" or similar.
190200

babel/util.py

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,26 @@
77
:copyright: (c) 2013-2022 by the Babel Team.
88
:license: BSD, see LICENSE for more details.
99
"""
10+
from __future__ import annotations
1011

1112
import codecs
1213
import collections
13-
from datetime import timedelta, tzinfo
1414
import os
1515
import re
1616
import textwrap
17+
from collections.abc import Generator, Iterable
18+
from datetime import datetime as datetime_, timedelta, tzinfo
19+
from typing import IO, Any, TypeVar
20+
1721
import pytz as _pytz
22+
1823
from babel import localtime
1924

2025
missing = object()
2126

27+
_T = TypeVar("_T")
2228

23-
def distinct(iterable):
29+
def distinct(iterable: Iterable[_T]) -> Generator[_T, None, None]:
2430
"""Yield all items in an iterable collection that are distinct.
2531
2632
Unlike when using sets for a similar effect, the original ordering of the
@@ -44,7 +50,7 @@ def distinct(iterable):
4450
br'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)', re.VERBOSE)
4551

4652

47-
def parse_encoding(fp):
53+
def parse_encoding(fp: IO[bytes]) -> str | None:
4854
"""Deduce the encoding of a source file from magic comment.
4955
5056
It does this in the same way as the `Python interpreter`__
@@ -96,7 +102,7 @@ def parse_encoding(fp):
96102
r'from\s+__future__\s+import\s+\(*(.+)\)*')
97103

98104

99-
def parse_future_flags(fp, encoding='latin-1'):
105+
def parse_future_flags(fp: IO[bytes], encoding: str = 'latin-1') -> int:
100106
"""Parse the compiler flags by :mod:`__future__` from the given Python
101107
code.
102108
"""
@@ -128,7 +134,7 @@ def parse_future_flags(fp, encoding='latin-1'):
128134
return flags
129135

130136

131-
def pathmatch(pattern, filename):
137+
def pathmatch(pattern: str, filename: str) -> bool:
132138
"""Extended pathname pattern matching.
133139
134140
This function is similar to what is provided by the ``fnmatch`` module in
@@ -200,7 +206,7 @@ class TextWrapper(textwrap.TextWrapper):
200206
)
201207

202208

203-
def wraptext(text, width=70, initial_indent='', subsequent_indent=''):
209+
def wraptext(text: str, width: int = 70, initial_indent: str = '', subsequent_indent: str = '') -> list[str]:
204210
"""Simple wrapper around the ``textwrap.wrap`` function in the standard
205211
library. This version does not wrap lines on hyphens in words.
206212
@@ -224,25 +230,25 @@ def wraptext(text, width=70, initial_indent='', subsequent_indent=''):
224230
class FixedOffsetTimezone(tzinfo):
225231
"""Fixed offset in minutes east from UTC."""
226232

227-
def __init__(self, offset, name=None):
233+
def __init__(self, offset: float, name: str | None = None):
228234
self._offset = timedelta(minutes=offset)
229235
if name is None:
230236
name = 'Etc/GMT%+d' % offset
231237
self.zone = name
232238

233-
def __str__(self):
239+
def __str__(self) -> str:
234240
return self.zone
235241

236-
def __repr__(self):
242+
def __repr__(self) -> str:
237243
return f'<FixedOffset "{self.zone}" {self._offset}>'
238244

239-
def utcoffset(self, dt):
245+
def utcoffset(self, dt: datetime_) -> timedelta:
240246
return self._offset
241247

242-
def tzname(self, dt):
248+
def tzname(self, dt: datetime_) -> str:
243249
return self.zone
244250

245-
def dst(self, dt):
251+
def dst(self, dt: datetime_) -> timedelta:
246252
return ZERO
247253

248254

0 commit comments

Comments
 (0)