0

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?

Petras Purlys
  • 1,093
  • 6
  • 18
  • Does this answer your question? [How to check if a python module exists without importing it](https://stackoverflow.com/questions/14050281/how-to-check-if-a-python-module-exists-without-importing-it) – mkrieger1 Feb 11 '22 at 17:59

1 Answers1

-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)
Jacek Błocki
  • 452
  • 3
  • 9
  • This is a good idea but here's a caveat: package "lxml" has a package "etree" that is not implemented in python meaning the actual file looks like this: "~/project/.venv/lib/python3.9/site-packages/lxml/etree.cpython-39-x86_64-linux-gnu.so" – Petras Purlys Feb 11 '22 at 17:07
  • Still it lxml.etree is an element of lxml package, thus lxml must be on sys.path. I guess you want to peek and decide what to import basing on available packages simple file check will do. – Jacek Błocki Feb 11 '22 at 18:05