From 05f26a9f533c4a43d99c5c6be5f9dac9886963d1 Mon Sep 17 00:00:00 2001 From: Tomas Roun Date: Sun, 15 Nov 2026 21:06:58 +0100 Subject: [PATCH 1/2] Remove some pytz compat code --- babel/dates.py | 34 +++++++---------------------- babel/localtime/_helpers.py | 43 ++++++++++--------------------------- babel/localtime/_unix.py | 2 +- docs/dates.rst | 9 ++++---- docs/dev.rst | 6 +++--- docs/installation.rst | 10 +++------ tests/test_localtime.py | 17 ++------------- 7 files changed, 33 insertions(+), 88 deletions(-) diff --git a/babel/dates.py b/babel/dates.py index 6f810c1d5..fa0d568db 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -17,21 +17,15 @@ from __future__ import annotations +import datetime import math import re import warnings +import zoneinfo +from collections.abc import Iterable from functools import lru_cache from typing import TYPE_CHECKING, Literal, SupportsInt -try: - import pytz -except ModuleNotFoundError: - pytz = None - import zoneinfo - -import datetime -from collections.abc import Iterable - from babel import localtime from babel.core import Locale, default_locale, get_global from babel.localedata import LocaleDataDict @@ -225,10 +219,7 @@ def _get_time( def get_timezone(zone: str | datetime.tzinfo | None = None) -> datetime.tzinfo: - """Looks up a timezone by name and returns it. The timezone object - returned comes from ``pytz`` or ``zoneinfo``, whichever is available. - It corresponds to the `tzinfo` interface and can be used with all of - the functions of Babel that operate with dates. + """Looks up a timezone by name and returns it. If a timezone is not known a :exc:`LookupError` is raised. If `zone` is ``None`` a local zone object is returned. @@ -241,19 +232,10 @@ def get_timezone(zone: str | datetime.tzinfo | None = None) -> datetime.tzinfo: if not isinstance(zone, str): return zone - if pytz: - try: - return pytz.timezone(zone) - except pytz.UnknownTimeZoneError as e: - exc = e - else: - assert zoneinfo - try: - return zoneinfo.ZoneInfo(zone) - except zoneinfo.ZoneInfoNotFoundError as e: - exc = e - - raise LookupError(f"Unknown timezone {zone}") from exc + try: + return zoneinfo.ZoneInfo(zone) + except zoneinfo.ZoneInfoNotFoundError as e: + raise LookupError(f"Unknown timezone {zone}") from e def get_period_names( diff --git a/babel/localtime/_helpers.py b/babel/localtime/_helpers.py index 75331785b..933f50a74 100644 --- a/babel/localtime/_helpers.py +++ b/babel/localtime/_helpers.py @@ -1,39 +1,21 @@ import zoneinfo -try: - import pytz -except ModuleNotFoundError: - pytz = None - def _get_tzinfo(tzenv: str): - """Get the tzinfo from `zoneinfo` or `pytz` + """Get the tzinfo from `zoneinfo` :param tzenv: timezone in the form of Continent/City :return: tzinfo object or None if not found """ - if pytz: - try: - return pytz.timezone(tzenv) - except pytz.UnknownTimeZoneError: - pass - else: - try: - return zoneinfo.ZoneInfo(tzenv) - except ValueError as ve: - # This is somewhat hacky, but since _validate_tzfile_path() doesn't - # raise a specific error type, we'll need to check the message to be - # one we know to be from that function. - # If so, we pretend it meant that the TZ didn't exist, for the benefit - # of `babel.localtime` catching the `LookupError` raised by - # `_get_tzinfo_or_raise()`. - # See https://github.com/python-babel/babel/issues/1092 - if str(ve).startswith("ZoneInfo keys "): - return None - except zoneinfo.ZoneInfoNotFoundError: - pass - - return None + try: + return zoneinfo.ZoneInfo(tzenv) + except (zoneinfo.ZoneInfoNotFoundError, ValueError): + # ValueError is raised for malformed keys. + # If that happens, we pretend it meant that the TZ didn't exist, + # for the benefit of `babel.localtime` catching the `LookupError` + # raised by `_get_tzinfo_or_raise()`. + # See https://github.com/python-babel/babel/issues/1092 + return None def _get_tzinfo_or_raise(tzenv: str): @@ -48,7 +30,4 @@ def _get_tzinfo_or_raise(tzenv: str): def _get_tzinfo_from_file(tzfilename: str): with open(tzfilename, 'rb') as tzfile: - if pytz: - return pytz.tzfile.build_tzinfo('local', tzfile) - else: - return zoneinfo.ZoneInfo.from_file(tzfile) + return zoneinfo.ZoneInfo.from_file(tzfile) diff --git a/babel/localtime/_unix.py b/babel/localtime/_unix.py index 70dd2322c..1b980968f 100644 --- a/babel/localtime/_unix.py +++ b/babel/localtime/_unix.py @@ -24,7 +24,7 @@ def _tz_from_env(tzenv: str) -> datetime.tzinfo: def _get_localzone(_root: str = '/') -> datetime.tzinfo: """Tries to find the local timezone configuration. This method prefers finding the timezone name and passing that to - zoneinfo or pytz, over passing in the localtime file, as in the later + zoneinfo, over passing in the localtime file, as in the later case the zoneinfo name is unknown. The parameter _root makes the function look for files like /etc/localtime beneath the _root directory. This is primarily used by the tests. diff --git a/docs/dates.rst b/docs/dates.rst index 33db59b75..6c971ea46 100644 --- a/docs/dates.rst +++ b/docs/dates.rst @@ -276,9 +276,10 @@ class, which you need appropriate implementations for to actually use in your application. Babel includes a ``tzinfo`` implementation for UTC (Universal Time). -Babel uses either `zoneinfo`_ or `pytz`_ for timezone support. -If pytz is installed, it is preferred over the standard library's zoneinfo. -You can directly interface with either of these modules from within Babel: +Babel uses the standard library `zoneinfo`_ module for timezone support. +Timezone objects from `pytz`_ are accepted wherever a ``tzinfo`` is required, +but Babel itself does not create them. You can directly interface with +``zoneinfo`` from within Babel: .. code-block:: pycon @@ -315,7 +316,7 @@ your operating system. It's provided through the ``LOCALTZ`` constant: >>> from babel.dates import LOCALTZ, get_timezone_name >>> LOCALTZ - + zoneinfo.ZoneInfo(key='Europe/Vienna') >>> get_timezone_name(LOCALTZ) 'Central European Time' diff --git a/docs/dev.rst b/docs/dev.rst index 552ca140a..74d5cd5fd 100644 --- a/docs/dev.rst +++ b/docs/dev.rst @@ -47,9 +47,9 @@ Unicode is a big deal in Babel. Here is how the rules are set up: Dates and Timezones ------------------- -Babel's timezone support relies on either ``pytz`` or ``zoneinfo``; if ``pytz`` -is installed, it is preferred over ``zoneinfo``. Babel should assume that any -timezone objects can be from either of these modules. +Babel's timezone support relies on ``zoneinfo``, however callers may still pass +``pytz`` timezone objects so Babel should assume that any timezone objects can +be from either of these modules. Assumptions to make: diff --git a/docs/installation.rst b/docs/installation.rst index 081cd651a..bdb6d2371 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -3,13 +3,9 @@ Installation ============ -Babel is distributed as a standard Python package fully set up with all -the dependencies it needs. On Python versions where the standard library -`zoneinfo`_ module is not available, `pytz`_ needs to be installed for -timezone support. If `pytz`_ is installed, it is preferred over the -standard library `zoneinfo`_ module where possible. - -.. _pytz: https://pythonhosted.org/pytz/ +Babel is distributed as a standard Python package fully set up with all the +dependencies it needs. Timezone support uses the standard library `zoneinfo`_ +module which reads the system's timezone database. .. _zoneinfo: https://docs.python.org/3/library/zoneinfo.html diff --git a/tests/test_localtime.py b/tests/test_localtime.py index 640576451..5ed4a8aba 100644 --- a/tests/test_localtime.py +++ b/tests/test_localtime.py @@ -4,27 +4,14 @@ import pytest -from babel.localtime import _helpers, get_localzone +from babel.localtime import get_localzone @pytest.mark.skipif( sys.platform == "win32", reason="Issue 1092 is not applicable on Windows", ) -def test_issue_1092_without_pytz(monkeypatch): - pytest.importorskip("zoneinfo", reason="zoneinfo is not available") - monkeypatch.setenv("TZ", "/UTC") # Malformed timezone name. - # In case pytz _is_ also installed, we want to pretend it's not, so patch it out... - monkeypatch.setattr(_helpers, "pytz", None) - with pytest.raises(LookupError): - get_localzone() - - -@pytest.mark.skipif( - sys.platform == "win32", - reason="Issue 1092 is not applicable on Windows", -) -def test_issue_1092_with_pytz(monkeypatch): +def test_issue_1092(monkeypatch): pytest.importorskip("pytz", reason="pytz is not installed") monkeypatch.setenv("TZ", "/UTC") # Malformed timezone name. with pytest.raises(LookupError): From b489f1b26ea7178a1532753f7b66e71c1c6b57c2 Mon Sep 17 00:00:00 2001 From: Tomas Roun Date: Tue, 17 Nov 2026 00:01:56 +0100 Subject: [PATCH 2/2] Increase test coverage --- tests/test_dates.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/test_dates.py b/tests/test_dates.py index 76a002bc3..b02593409 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -285,6 +285,11 @@ def test_get_time_format(): 'HH:mm:ss zzzz') +def test_get_timezone_unknown(): + with pytest.raises(LookupError): + dates.get_timezone("DoesNot/Exist") + + def test_get_timezone_gmt(timezone_getter): dt = datetime(2007, 4, 1, 15, 30) assert dates.get_timezone_gmt(dt, locale='en') == 'GMT+00:00'