I want to ensure all modules within one package ("pkg-foo
") don't import from another package ("pkg-block
").
Update: I know there are many black magic ways to import modules due to Python's dynamism. However, I am only interested in checking explicit imports (e.g. import pkg.block
or from pkg.block import ...
).
I want to enforce this via a unit test in pkg-foo
that ensures it never imports from pkg-block
.
How can I accomplish this? I use Python 3.8+ and am looking to use either built-ins or perhaps setuptools
.
Current Half-Baked Solution
# pkg_resources is from setuptools
from pkg_resources import Distribution, working_set
# Confirm pgk-block is not in pkg-foo's install_requires
foo_pkg: Distribution = working_set.by_key[f"foo-pkg"]
for req in foo_pkg.requires():
assert "pkg-block" not in str(req)
However, just because pkg-block
is not declared in setup.py
's install_requires
doesn't mean it wasn't imported within the package. So, this is only a half-baked solution.
My thoughts are I need to crawl all modules within pkg-foo
and check each module doesn't import from pgk-block
.