'How to determine if some name refers to a module without actually importing it in python?
I'm aware of two python functions that can be used to determine if some name refers to a module: pkgutil.find_loader(fullname) and pkgutil.resolve_name(name). The first method returns a loader if the input is an importable module name. The second option returns an object whose type can be inspected to determine if it's a module. However, in both of these cases the module in question actually gets imported to python - something I do not wish to happen. Is there a way to determine if a name refers to a module (package) without actually importing it?
Solution 1:[1]
If a module is either a .py file, or a directory containing init.py in one of sys.path directories then below function may help:
def ismodule(fn):
for i in sys.path:
if os.path.isfile(os.path.join(i, fn) + '.py'): return (True, i)
if os.path.isfile(os.path.join(i, fn, '__init__.py')): return (True, os.path.join(i, fn))
return (False, None)
version below covers sub-modules:
def ismodule(fn):
fnm = fn.split('.')[0]
for i in sys.path:
if os.path.isfile(os.path.join(i, fnm) + '.py'): return (True, i, fnm)
if os.path.isfile(os.path.join(i, fnm, '__init__.py')): return (True, os.path.join(i, fnm), fnm)
return (False, None, fnm)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
