I am attempting to access some functions in file that’s one directory below the file where I want to use them. I am looking to do this in a dynamic fashion, as I will not know prior to runtime which functions the user will want to use.
I will ask the user for a particular scenario, for example, and if they request the 1424 scenario, I would like to have access to functions in a ‘scenarios/scenario1424.py’ file.
I am looking to do this using importlib.import_module(…), but I can’t seem to have it let me access those functions even though I seem to be successfully importing the file module.
Directory structure:
code/
- main.py
scenarios/
- __init__.py (empty)
- scenario1420.py
- scenario1421.py
- scenario1424.py
Inside a scenario file, I’ll have a bunch of methods defined like so:
def run():
.......
def compute():
.......
I seemed to be able to import the module using importlib.import_module('scenarios.scenario1424') (returns <module 'scenarios.scenario1424' from 'scenarios/scenario1424.pyc'>), but when I attempt to access a function like: scenario1424.run() , I get a NameError (NameError: name 'scenario1424' is not defined).
Any thoughts?
import_modulereturns the module object itself, it is your own responsibility to assign it to a name you can use. So in your case it would bescenario1424 = importlib.import_module('scenarios.scenario1424')