Skip to content

Commit

Permalink
Merge branch 'master' into joe/updates-ignore-pot-creation-date
Browse files Browse the repository at this point in the history
  • Loading branch information
joeportela committed Jul 5, 2023
2 parents 254a81a + 1747d22 commit 620fc1d
Show file tree
Hide file tree
Showing 17 changed files with 72 additions and 52 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.247
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.275
hooks:
- id: ruff
args:
Expand Down
27 changes: 15 additions & 12 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def _get_tz_name(dt_or_tzinfo: _DtOrTzinfo) -> str:
elif hasattr(tzinfo, 'key') and tzinfo.key is not None: # ZoneInfo object
return tzinfo.key
else:
return tzinfo.tzname(dt or datetime.datetime.utcnow())
return tzinfo.tzname(dt or datetime.datetime.now(UTC))


def _get_datetime(instant: _Instant) -> datetime.datetime:
Expand Down Expand Up @@ -147,9 +147,9 @@ def _get_datetime(instant: _Instant) -> datetime.datetime:
:rtype: datetime
"""
if instant is None:
return datetime.datetime.utcnow()
return datetime.datetime.now(UTC).replace(tzinfo=None)
elif isinstance(instant, (int, float)):
return datetime.datetime.utcfromtimestamp(instant)
return datetime.datetime.fromtimestamp(instant, UTC).replace(tzinfo=None)
elif isinstance(instant, datetime.time):
return datetime.datetime.combine(datetime.date.today(), instant)
elif isinstance(instant, datetime.date) and not isinstance(instant, datetime.datetime):
Expand Down Expand Up @@ -201,9 +201,9 @@ def _get_time(
:rtype: time
"""
if time is None:
time = datetime.datetime.utcnow()
time = datetime.datetime.now(UTC)
elif isinstance(time, (int, float)):
time = datetime.datetime.utcfromtimestamp(time)
time = datetime.datetime.fromtimestamp(time, UTC)

if time.tzinfo is None:
time = time.replace(tzinfo=UTC)
Expand Down Expand Up @@ -538,11 +538,11 @@ def get_timezone_name(
>>> from datetime import time
>>> dt = time(15, 30, tzinfo=get_timezone('America/Los_Angeles'))
>>> get_timezone_name(dt, locale='en_US')
>>> get_timezone_name(dt, locale='en_US') # doctest: +SKIP
u'Pacific Standard Time'
>>> get_timezone_name(dt, locale='en_US', return_zone=True)
'America/Los_Angeles'
>>> get_timezone_name(dt, width='short', locale='en_US')
>>> get_timezone_name(dt, width='short', locale='en_US') # doctest: +SKIP
u'PST'
If this function gets passed only a `tzinfo` object and no concrete
Expand Down Expand Up @@ -774,10 +774,10 @@ def format_time(
>>> t = time(15, 30)
>>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
... locale='fr_FR')
... locale='fr_FR') # doctest: +SKIP
u'15:30:00 heure normale d\u2019Europe centrale'
>>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'),
... locale='en_US')
... locale='en_US') # doctest: +SKIP
u'3:30:00\u202fPM Eastern Standard Time'
:param time: the ``time`` or ``datetime`` object; if `None`, the current
Expand Down Expand Up @@ -922,9 +922,12 @@ def format_timedelta(
if format not in ('narrow', 'short', 'medium', 'long'):
raise TypeError('Format must be one of "narrow", "short" or "long"')
if format == 'medium':
warnings.warn('"medium" value for format param of format_timedelta'
' is deprecated. Use "long" instead',
category=DeprecationWarning)
warnings.warn(
'"medium" value for format param of format_timedelta'
' is deprecated. Use "long" instead',
category=DeprecationWarning,
stacklevel=2,
)
format = 'long'
if isinstance(delta, datetime.timedelta):
seconds = int((delta.days * 86400) + delta.seconds)
Expand Down
2 changes: 1 addition & 1 deletion babel/lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def format_list(lst: Sequence[str],
A typical 'and' list for arbitrary placeholders.
eg. "January, February, and March"
* standard-short:
A short version of a 'and' list, suitable for use with short or abbreviated placeholder values.
A short version of an 'and' list, suitable for use with short or abbreviated placeholder values.
eg. "Jan., Feb., and Mar."
* or:
A typical 'or' list for arbitrary placeholders.
Expand Down
8 changes: 4 additions & 4 deletions babel/messages/checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ def _check_positional(results: list[tuple[str, str]]) -> bool:
if name not in type_map:
raise TranslationError(f'unknown named placeholder {name!r}')
elif not _compatible(typechar, type_map[name]):
raise TranslationError('incompatible format for '
'placeholder %r: '
'%r and %r are not compatible' %
(name, typechar, type_map[name]))
raise TranslationError(
f'incompatible format for placeholder {name!r}: '
f'{typechar!r} and {type_map[name]!r} are not compatible'
)


def _find_checkers() -> list[Callable[[Catalog | None, Message], object]]:
Expand Down
2 changes: 1 addition & 1 deletion babel/messages/plurals.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ class _PluralTuple(tuple):
The number of plurals used by the locale.""")
plural_expr = property(itemgetter(1), doc="""
The plural expression used by the locale.""")
plural_forms = property(lambda x: 'nplurals=%s; plural=%s;' % x, doc="""
plural_forms = property(lambda x: 'nplurals={}; plural={};'.format(*x), doc="""
The plural expression used by the catalog or locale.""")

def __str__(self) -> str:
Expand Down
8 changes: 6 additions & 2 deletions babel/numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def format_number(number: float | decimal.Decimal | str, locale: Locale | str |
"""
warnings.warn('Use babel.numbers.format_decimal() instead.', DeprecationWarning)
warnings.warn('Use babel.numbers.format_decimal() instead.', DeprecationWarning, stacklevel=2)
return format_decimal(number, locale=locale)


Expand Down Expand Up @@ -1190,7 +1190,11 @@ def apply(
# currency's if necessary.
if force_frac:
# TODO (3.x?): Remove this parameter
warnings.warn('The force_frac parameter to NumberPattern.apply() is deprecated.', DeprecationWarning)
warnings.warn(
'The force_frac parameter to NumberPattern.apply() is deprecated.',
DeprecationWarning,
stacklevel=2,
)
frac_prec = force_frac
elif currency and currency_digits:
frac_prec = (get_currency_precision(currency), ) * 2
Expand Down
2 changes: 1 addition & 1 deletion babel/plural.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
def extract_operands(source: float | decimal.Decimal) -> tuple[decimal.Decimal | int, int, int, int, int, int, Literal[0], Literal[0]]:
"""Extract operands from a decimal, a float or an int, according to `CLDR rules`_.
The result is a 8-tuple (n, i, v, w, f, t, c, e), where those symbols are as follows:
The result is an 8-tuple (n, i, v, w, f, t, c, e), where those symbols are as follows:
====== ===============================================================
Symbol Value
Expand Down
28 changes: 20 additions & 8 deletions babel/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,8 +393,11 @@ def ldgettext(self, domain: str, message: str) -> str:
domain.
"""
import warnings
warnings.warn('ldgettext() is deprecated, use dgettext() instead',
DeprecationWarning, 2)
warnings.warn(
'ldgettext() is deprecated, use dgettext() instead',
DeprecationWarning,
stacklevel=2,
)
return self._domains.get(domain, self).lgettext(message)

def udgettext(self, domain: str, message: str) -> str:
Expand All @@ -416,8 +419,11 @@ def ldngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
domain.
"""
import warnings
warnings.warn('ldngettext() is deprecated, use dngettext() instead',
DeprecationWarning, 2)
warnings.warn(
'ldngettext() is deprecated, use dngettext() instead',
DeprecationWarning,
stacklevel=2,
)
return self._domains.get(domain, self).lngettext(singular, plural, num)

def udngettext(self, domain: str, singular: str, plural: str, num: int) -> str:
Expand Down Expand Up @@ -458,8 +464,11 @@ def lpgettext(self, context: str, message: str) -> str | bytes | object:
``bind_textdomain_codeset()``.
"""
import warnings
warnings.warn('lpgettext() is deprecated, use pgettext() instead',
DeprecationWarning, 2)
warnings.warn(
'lpgettext() is deprecated, use pgettext() instead',
DeprecationWarning,
stacklevel=2,
)
tmsg = self.pgettext(context, message)
encoding = getattr(self, "_output_charset", None) or locale.getpreferredencoding()
return tmsg.encode(encoding) if isinstance(tmsg, str) else tmsg
Expand Down Expand Up @@ -493,8 +502,11 @@ def lnpgettext(self, context: str, singular: str, plural: str, num: int) -> str
``bind_textdomain_codeset()``.
"""
import warnings
warnings.warn('lnpgettext() is deprecated, use npgettext() instead',
DeprecationWarning, 2)
warnings.warn(
'lnpgettext() is deprecated, use npgettext() instead',
DeprecationWarning,
stacklevel=2,
)
ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
try:
tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
Expand Down
2 changes: 1 addition & 1 deletion babel/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def get_unit_name(

def _find_unit_pattern(unit_id: str, locale: Locale | str | None = LC_NUMERIC) -> str | None:
"""
Expand an unit into a qualified form.
Expand a unit into a qualified form.
Known units can be found in the CLDR Unit Validity XML file:
https://unicode.org/repos/cldr/tags/latest/common/validity/unit.xml
Expand Down
2 changes: 1 addition & 1 deletion contrib/babel.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

/**
* A simple module that provides a gettext like translation interface.
* The catalog passed to load() must be a object conforming to this
* The catalog passed to load() must be an object conforming to this
* interface::
*
* {
Expand Down
6 changes: 3 additions & 3 deletions docs/dates.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ local time when returning dates to users. At that point the timezone the
user has selected can usually be established and Babel can automatically
rebase the time for you.

To get the current time use the :meth:`~datetime.datetime.utcnow` method
of the :class:`~datetime.datetime` object. It will return a naive
:class:`~datetime.datetime` object in UTC.
To get the current time use the :meth:`~datetime.datetime.now` method
of the :class:`~datetime.datetime` object,
passing :attr:`~datetime.timezone.utc` to it as the timezone.

For more information about timezones see :ref:`timezone-support`.

Expand Down
8 changes: 4 additions & 4 deletions scripts/import_cldr.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,25 +525,25 @@ def parse_dates(data, tree, sup, regions, territory):
if _should_skip_elem(elem):
continue
territories = elem.attrib['territories'].split()
if territory in territories or any([r in territories for r in regions]):
if territory in territories or any(r in territories for r in regions):
week_data['min_days'] = int(elem.attrib['count'])
for elem in supelem.findall('firstDay'):
if _should_skip_elem(elem):
continue
territories = elem.attrib['territories'].split()
if territory in territories or any([r in territories for r in regions]):
if territory in territories or any(r in territories for r in regions):
week_data['first_day'] = weekdays[elem.attrib['day']]
for elem in supelem.findall('weekendStart'):
if _should_skip_elem(elem):
continue
territories = elem.attrib['territories'].split()
if territory in territories or any([r in territories for r in regions]):
if territory in territories or any(r in territories for r in regions):
week_data['weekend_start'] = weekdays[elem.attrib['day']]
for elem in supelem.findall('weekendEnd'):
if _should_skip_elem(elem):
continue
territories = elem.attrib['territories'].split()
if territory in territories or any([r in territories for r in regions]):
if territory in territories or any(r in territories for r in regions):
week_data['weekend_end'] = weekdays[elem.attrib['day']]
zone_formats = data.setdefault('zone_formats', {})
for elem in tree.findall('.//timeZoneNames/gmtFormat'):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def run(self):
author_email='[email protected]',
maintainer='Aarni Koskela',
maintainer_email='[email protected]',
license='BSD',
license='BSD-3-Clause',
url='https://babel.pocoo.org/',
project_urls={
'Source': 'https://github.com/python-babel/babel',
Expand Down
2 changes: 1 addition & 1 deletion tests/messages/test_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ def test_catalog_update():
assert len(cat) == 3

msg1 = cat['green']
msg1.string
assert not msg1.string
assert msg1.locations == [('main.py', 99)]

msg2 = cat['blue']
Expand Down
2 changes: 1 addition & 1 deletion tests/messages/test_plurals.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def test_get_plural_selection(locale, num_plurals, plural_expr):
assert plurals.get_plural(locale) == (num_plurals, plural_expr)


def test_get_plural_accpets_strings():
def test_get_plural_accepts_strings():
assert plurals.get_plural(locale='ga') == (5, '(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)')


Expand Down
17 changes: 9 additions & 8 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import pytest

from babel import Locale, dates
from babel.dates import NO_INHERITANCE_MARKER, _localize
from babel.dates import NO_INHERITANCE_MARKER, UTC, _localize
from babel.util import FixedOffsetTimezone


Expand Down Expand Up @@ -542,7 +542,7 @@ def test_get_timezone_name_time_pytz(timezone_getter, tzname, params, expected):


def test_get_timezone_name_misc(timezone_getter):
localnow = datetime.utcnow().replace(tzinfo=timezone_getter('UTC')).astimezone(dates.LOCALTZ)
localnow = datetime.now(timezone_getter('UTC')).astimezone(dates.LOCALTZ)
assert (dates.get_timezone_name(None, locale='en_US') ==
dates.get_timezone_name(localnow, locale='en_US'))

Expand Down Expand Up @@ -601,12 +601,13 @@ def test_format_time(timezone_getter):
custom = dates.format_time(t, "hh 'o''clock' a, zzzz", tzinfo=eastern, locale='en')
assert custom == "09 o'clock AM, Eastern Daylight Time"

t = time(15, 30)
paris = dates.format_time(t, format='full', tzinfo=paris, locale='fr_FR')
assert paris == '15:30:00 heure normale d’Europe centrale'
with freezegun.freeze_time("2023-01-01"):
t = time(15, 30)
paris = dates.format_time(t, format='full', tzinfo=paris, locale='fr_FR')
assert paris == '15:30:00 heure normale d’Europe centrale'

us_east = dates.format_time(t, format='full', tzinfo=eastern, locale='en_US')
assert us_east == '3:30:00\u202fPM Eastern Standard Time'
us_east = dates.format_time(t, format='full', tzinfo=eastern, locale='en_US')
assert us_east == '3:30:00\u202fPM Eastern Standard Time'


def test_format_skeleton(timezone_getter):
Expand Down Expand Up @@ -702,7 +703,7 @@ def test_zh_TW_format():


def test_format_current_moment():
frozen_instant = datetime.utcnow()
frozen_instant = datetime.now(UTC)
with freezegun.freeze_time(time_to_freeze=frozen_instant):
assert dates.format_datetime(locale="en_US") == dates.format_datetime(frozen_instant, locale="en_US")

Expand Down
2 changes: 1 addition & 1 deletion tests/test_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def raise_attribute_error():

proxy = support.LazyProxy(raise_attribute_error)
with pytest.raises(AttributeError) as exception:
proxy.value
_ = proxy.value

assert str(exception.value) == 'message'

Expand Down

0 comments on commit 620fc1d

Please sign in to comment.