__import__()

The built-in __import__() function allows you to dynamically import a module by its name, which should be provided as a string:

Python
>>> sys = __import__("sys")
>>> sys
<module 'sys' (built-in)>

__import__() Signature

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

Arguments

Argument Description Default Value
name A module’s name as a string Required argument
globals A dictionary representing the global namespace None
locals A dictionary representing the local namespace None
fromlist A list of objects or submodules to import from the module ()
level Number of parent directories to search for relative imports 0

Return Value

  • Returns the top-level package or module specified by name when the fromlist argument is empty.
  • Returns the module specified by name when fromlist is not empty.

__import__() Examples

With a simple module name as an argument:

Python
>>> math = __import__("math")
>>> math.sqrt(16)
4.0

With a module and submodule specified in name and using fromlist:

Python
>>> os_path = __import__("os.path", fromlist=[""])
>>> os_path
<module 'posixpath' (frozen)>

__import__() Common Use Cases

The most common use cases for the __import__() function include:

  • Implementing custom import logic in advanced applications.
  • Dynamically importing modules based on string input.
  • Overriding the import system for specialized needs.

__import__() Real-World Example

Suppose you want to dynamically import a module based on user input, allowing for flexible program behavior:

Python
>>> module_name = input("Enter module name to import: ")
>>> module = __import__(module_name)
>>> print(f"{module_name} module has been imported.")

This example demonstrates how __import__() can be used to dynamically import a module, enhancing flexibility in applications where the module to be imported is determined at runtime.

Related Resources

Tutorial

Python import: Advanced Techniques and Tips

The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 12, 2024 • Reviewed by Dan Bader