I am working with Python libraries and frameworks like TensorFlow and PyTorch, and doing various manipulations and inferences on their interfaces. Executing slows things down and causes compatibility issues. How do I find the module filepath?
Old version (that works but exec
s):
from os import path
from importlib.util import find_spec
def find_module_filepath(module_name, submodule_name):
"""
Find module's file location without first importing it
:param module_name: Module name, e.g., "cdd.tests"
:type: ```str```
:param submodule_name: Submodule name, e.g., "test_pure_utils"
:type: ```str```
:return: Module location
:rpath: ```str```
"""
module_spec = find_spec(module_name)
assert module_spec is not None, "spec not found for {}".format(module_name)
module_origin = module_spec.origin
module_parent = path.dirname(module_origin)
return next(
filter(
path.exists,
(
path.join(
module_parent, submodule_name, "__init__{}py".format(path.extsep)
),
path.join(module_parent, "{}{}py".format(submodule_name, path.extsep)),
path.join(
module_parent, submodule_name, "__init__{}py".format(path.extsep)
),
),
),
module_origin,
)
Specifically I am asking for how module resolution works; assuming that each module is already referencing an actual filesystem location.
Is it something like: first sys.path
then PYTHONPATH
then distutils.sysconfig.get_python_lib
? - And do I just build a tree in memory using os.walk
?