1

Is there a way to "reference" a module from a string? For example, the following is quite repetitive:

module = "module1"

if module == "module1":
    module1.function1()
elif module == "module2":
    module2.function1()
elif module == "module3":
    module3.function1()

# Other code...

if module == "module1":
    module1.function2()
elif module == "module2":
    module2.function2()
elif module == "module3":
    module3.function2()

So I was wondering if there was a better way to do it, for example exec(module).function1() (which, doesn't work and probably is unsafe too...)

Alternatively, is there a better way of coding this type of thing? Each file is for different sites but have the same functions.

1
  • 1
    You could just set module = module1 (or module2 or module 3) and run module.function1(), etc. Commented May 12, 2020 at 16:50

1 Answer 1

3

If your strings and your module names differ, you can set up a dict at the beginning of the program:

import module1
import module2

modules = {
  "module1": module1,
  "module2": module2,
  ...
}
...

modules[moduleName].function1()
modules[moduleName].function2()

If your strings are always the same as the names of the modules, then you might be able to use importlib:

from importlib import import_module

...

import_module(moduleName).function1()
import_module(moduleName).function2()
Sign up to request clarification or add additional context in comments.

3 Comments

You can also use builtin __import__ function instead of import_module function.
Thank you! Do you know if it is possible to do the same for a from import? So from modules import module1 in this method. I've tried __import__("modules.module1"), which doesn't work.
Nevermind, importlib works for that. Thanks again!!

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.