What's the best approach to execute the following using __import__
so that I may dynamically specify the module?
from module import *
__import__() . This means all semantics of the function are derived from importlib. __import__() . The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg. mod ), while __import__() returns the top-level package or module (e.g. pkg ).
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.
It just means that you import all(methods, variables,...) in a way so you don't need to prefix them when using them.
The import_module() function acts as a simplifying wrapper around importlib. __import__(). This means all semantics of the function are derived from importlib. __import__(), including requiring the package from which an import is occurring to have been previously imported (i.e., package must already be imported).
The only way I found:
module = __import__(module, globals(), locals(), ['*'])
for k in dir(module):
locals()[k] = getattr(module, k)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With