Search code examples
pythonpython-3.7python-importlib

importlib not working for files in subdirectory


I have a directory structure like this :

__init__.py
test.py
dir1/
    __init__.py
    dir2
        __init__.py
        myfile.py

There might be more py files inside dir2. So I want to import them at run time and load all classes defined inside these files.

test.py:

import inspect
import importlib

module = importlib.import_module('dir1/dir2/myfile.py')
for name, obj in inspect.getmembers(module):
    if inspect.isclass(module):
        print(obj.id)   # id is defined in all the classes

This gives me error while doing import_module :

ModuleNotFoundError: No module named 'dir1/dir2/myfile'

I've tried to append dir1/dir2 path to sys.path and then import myfile.py, which doesn't work either. Also the similar code works is myfile.py is placed at same level as test.py.

Python version : 3.7


Solution

  • Just reiterating for the sake of clarity:

    import_module() only accepts dotted module paths, not filenames. E.g., importlib.import_module('dir1.dir2.myfile')