Python __import__()

The __import__() is an advanced function that is called by the import statement.

The syntax of __import__() function is:

__import__(name, globals=None, locals=None, fromlist=(), level=0)

__import__() Parameters

  • name - name of the module you want to import
  • globals and locals - determines how to interpert name
  • fromlist - objects or submodules that should be imported by name
  • level - specifies whether to use absolute or relative imports

Use of __import__() is Discoraged

This __import__() function is not necessary in everyday Python programming. It is rarely used and often discouraged.

This function can be used to changed the semantics of import statement as import statement calls this function. However, it is always better to use import hooks.

If you want to import a module by name, use importlib.import_module() instead.

Example: How __import()__ works?

mathematics = __import__('math', globals(), locals(), [], 0)


When you run the program, the output will be:


In general, fabs() is a method defined in math module. You can call this function using the following syntax:


However, using __import__() changed the way to access fabs() in the above program.