Search code examples
pythongetattrpython-importlib

Python: Import function from file whose name is a variable


I have a file ./model_scripts/medians.py containing a function predict_volume(). [Output of tree in the bash terminal given below]

 model_scripts
 ├── __init__.py
 ├── medians.py
 └── ...

I need to import this function into another python script where the name of the python script from which the function must be imported (i.e. medians.py) is in the form of a string variable. The code I have written is:

model_name = 'medians'
...
model = getattr(__import__('model_scripts'), model_name)
vol = model.predict_volume()

But I get the following error at the first line:

AttributeError: 'module' object has no attribute 'medians'

Upon reading other answers (here), I added a __init__.py to the model_scripts directory. But I am still getting the above error.

This answer suggested using importlib:

import importlib
model_name = 'medians'
...
model = importlib.import_module('model_scripts.'+model_name)
vol = model.predict_volume()

Would appreciate any insights on why the first approach does not work but the second does.


Solution

  • The correct syntax for __import__ here is using fromlist along with it.

    The following works (read here):

    model = getattr(__import__('model_scripts', fromlist=[model_name]), model_name)