Skip to content

Commit 2a538f9

Browse files
feat: Use importlib.resources to load package files (#633)
* feat: Use importlib.resources to load package files * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent df88b0e commit 2a538f9

File tree

4 files changed

+51
-19
lines changed

4 files changed

+51
-19
lines changed

pendulum/locales/locale.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import os
21
import re
2+
import sys
33

44
from importlib import import_module
55
from typing import Any
@@ -8,6 +8,12 @@
88
from typing import Union
99

1010

11+
if sys.version_info >= (3, 9):
12+
from importlib import resources
13+
else:
14+
import importlib_resources as resources
15+
16+
1117
class Locale:
1218
"""
1319
Represent a specific locale.
@@ -31,8 +37,8 @@ def load(cls, locale: Union[str, "Locale"]) -> "Locale":
3137

3238
# Checking locale existence
3339
actual_locale = locale
34-
locale_path = os.path.join(os.path.dirname(__file__), actual_locale)
35-
while not os.path.exists(locale_path):
40+
locale_path = resources.files(__package__).joinpath(actual_locale)
41+
while not locale_path.exists():
3642
if actual_locale == locale:
3743
raise ValueError(f"Locale [{locale}] does not exist.")
3844

pendulum/tz/__init__.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import os
1+
import sys
22

33
from typing import Union
44

@@ -12,6 +12,12 @@
1212
from .timezone import Timezone
1313

1414

15+
if sys.version_info >= (3, 9):
16+
from importlib import resources
17+
else:
18+
import importlib_resources as resources
19+
20+
1521
PRE_TRANSITION = "pre"
1622
POST_TRANSITION = "post"
1723
TRANSITION_ERROR = "error"
@@ -26,7 +32,7 @@ def timezones():
2632
global _timezones
2733

2834
if _timezones is None:
29-
with open(os.path.join(os.path.dirname(tzdata.__file__), "zones")) as f:
35+
with open(resources.files(tzdata).joinpath("zones")) as f:
3036
_timezones = tuple(tz.strip() for tz in f.readlines())
3137

3238
return _timezones

poetry.lock

Lines changed: 33 additions & 14 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ python = "^3.7"
2929
python-dateutil = "^2.6"
3030
"backports.zoneinfo" = {version = "^0.2.1", python = ">=3.7,<3.9"}
3131
tzdata = ">=2020.1"
32+
importlib-resources = {version = "^5.9.0", python = ">=3.7,<3.9"}
3233

3334
[tool.poetry.group.test.dependencies]
3435
pytest = "^6.2.5"

0 commit comments

Comments
 (0)