Skip to content

Commit 3374958

Browse files
authored
Merge pull request #10 from davisagli/missing-pkg_resources
Handle missing pkg_resources gracefully
2 parents e784007 + b63e782 commit 3374958

File tree

3 files changed

+18
-5
lines changed

3 files changed

+18
-5
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Changelog
22

3+
- 2025-11-05:
4+
Make the `pkg_resources.declare_namespace` patch work even if there's no longer a real `pkg_resources` module.
35
- 2025-11-05:
46
Fix handling of namespaces that have an `__init__.py` installed.
57
Now we read the namespaces from `*.dist-info/namespace_packages.txt` instead of looking for modules that were loaded with NamespaceLoader.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
# SPDX-FileCopyrightText: 2025 David Glick <[email protected]>
22
#
33
# SPDX-License-Identifier: MIT
4-
__version__ = "20251105.0"
4+
__version__ = "20251105.1"

src/horse_with_no_namespace/pkg_resources.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,21 @@ def _lazy_load_pkg_resources():
4747
# This is called when something from pkg_resources is accessed.
4848
# We import it here to avoid importing it at the top of the file,
4949
# which would cause a circular import.
50-
del sys.modules["pkg_resources"]
51-
import pkg_resources
52-
53-
pkg_resources.declare_namespace = declare_namespace
50+
# But let's be careful in case the real pkg_resources isn't available...
51+
existing_pkg_resources = sys.modules["pkg_resources"]
52+
try:
53+
del sys.modules["pkg_resources"]
54+
import pkg_resources
55+
except ModuleNotFoundError:
56+
# There is no actual pkg_resources module
57+
# (maybe it's a new version of setuptools that removed it).
58+
# So keep this stub and stop trying to replace it.
59+
pkg_resources = sys.modules["pkg_resources"] = existing_pkg_resources
60+
del globals()["__getattr__"]
61+
del globals()["__dir__"]
62+
else:
63+
# Patch the real pkg_resources to use our declare_namespace function.
64+
pkg_resources.declare_namespace = declare_namespace
5465
_pkg_resources = pkg_resources
5566

5667

0 commit comments

Comments
 (0)