Daedalus Mythos
Daedalus Mythos

Reputation: 575

Unable to use dynamically imported modules

I'm dynamically importing any .py modules that are not the __init__.py or my skeleton.py files from a subdirectory. I first build a list that looks like (.py is omitted):

mods_in_dir = ['my_mods.frst_mod','my_mods.scnd_mod']

my_mods beign the subdirectory, frst_mod.py and sncd_mod.py being the available modules. All modules I import contain the class Operation and it offers always the same three functions. Then I import them using importlib.

import importlib

imports = {}

for i in mods_in_dir:
   imports[i] = importlib.import_module(i)

Which results in apparently successful imports, as I checked it by print(sys.modules.keys()), where they show up as [...], 'my_mods.frst_mod', 'my_mods.scnd_mod', [...].

For testing reasons I defined a function in every of the modules:

def return_some_string():
    return "some string"

But I'm unable to call this function. I've tried everything that came to my mind.. e.g. print(my_mods.frst_mod.Operation.return_some_string()) or print(frst_mod.Operation.return_some_string())

Both resulting in NameError: name 'my_mods' is not defined or NameError: name 'frst_mod' is not defined

edit: Solved.

@m170897017 helped me solve the problem in my initial attempt. I missed that I had the modules in the imports dict and didn't use that.

print(imports['my_mods.frst_mod'].ModsClassName.return_some_string()) now successfully prints some_string

Upvotes: 0

Views: 61

Answers (1)

Stephen Lin
Stephen Lin

Reputation: 4912

Change dynamic import to this way and try again:

...
mods_in_dir = ['my_mods.frst_mod','my_mods.scnd_mod']
modules = list(map(__import__, mods_in_dir))
# if you want to invoke func1 in my_mods.frst_mod and get result from it
result1 = modules[0].func1()
# if you want to invoke func2 in my_mods.scnd_mod and get result from it
result2 = modules[1].func2()
...

Upvotes: 1

Related Questions