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.

4
  • 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. Commented Mar 7, 2017 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? Commented Mar 7, 2017 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? Commented Mar 7, 2017 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. Commented Mar 8, 2017 at 7:27

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.