89DEVs

Python __import__() function

overview of __import__()

The __import__() function is used to change the behavior of the import statement. The import statement actually calls the __import__() function. The use of the function is discouraged and the preferred way of changing the import behavior is by using import hooks.

use of __import__()

The __import__() function can be used to change the behavior of the import statement. # use of __import__() np = __import__('numpy', globals(), locals(), [], 0) a = np.zeros( 10, int ) print(a) The __import__() function is used to import the numpy module as np. It allows us to call numpy methods using np.method() calls. [0 0 0 0 0 0 0 0 0 0]

syntax of __import__()

The sytnax of the __import__() function is: __import__(name[, globals=None, locals=None, fromlist=(), level=0])

arguments of __import__()

The import function requires at least one argument, the name argument. It has also four more additional arguments.
argument required description
name required the name of the module to be imported
globals optional globals and locals to determine how to interpret the name
fromlist optional objects or submodules to be imported by name
levels optional the level defines if absolute or relative imports are used
If no argument is passed an TypeError exception is raised: TypeError: __import__() missing required argument 'name' (pos 1)

                
        

Summary


Click to jump to section