Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import * with __import__

Tags:

python

import

What's the best approach to execute the following using __import__ so that I may dynamically specify the module?

from module import *
like image 268
David Cramer Avatar asked May 26 '10 20:05

David Cramer


People also ask

What is __ import __ in Python?

__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 ).

Should we import * in Python?

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.

What does from file import * do?

It just means that you import all(methods, variables,...) in a way so you don't need to prefix them when using them.

What does Importlib import_module do?

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).


1 Answers

The only way I found:

module = __import__(module, globals(), locals(), ['*'])
for k in dir(module):
    locals()[k] = getattr(module, k)
like image 102
David Cramer Avatar answered Oct 03 '22 15:10

David Cramer