2

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.

Community
  • 1
  • 1
IM94
  • 153
  • 1
  • 12
  • The first is equivalent to `from model_scripts import medians` and the second is equivalent to `import model_scripts.medians`, which are two different requests. – cdhowie Mar 07 '17 at 19:38
  • @cdhowie: Isn't what I'm doing by typing ` model = getattr(__import__('model_scripts'), model_name)` the same as `model = model_scripts.medians`? – IM94 Mar 07 '17 at 19:40
  • It should be. This assumes that `model_scripts` even exports `medians`. Does `from model_scripts import medians` work the way you think it should? – cdhowie Mar 07 '17 at 20:00
  • @cdhowie: Yes, it works as expected. However, if the module name 'medians' is a string variable, I cannot import it that way. – IM94 Mar 08 '17 at 07:27

1 Answers1

3

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)
Community
  • 1
  • 1
Shashank Dixena
  • 339
  • 2
  • 9