Python __import__()
Function
The __import__()
function in Python is a special built-in function that is used to import modules dynamically at runtime. While you typically use the import
keyword, this function is what Python uses behind the scenes to make that happen.
Syntax
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Parameters:
name
– Required. The name of the module to import (as a string).globals
– Optional. Usuallyglobals()
.locals
– Optional. Usuallylocals()
.fromlist
– Optional. A list of names to import from the module.level
– Optional. Used for relative imports (0 = absolute import).
Returns:
- The imported module object.
Basic Example
math_module = __import__('math')
print(math_module.sqrt(16))
4.0
Using fromlist
Parameter
If you want to import specific objects (like sqrt
or pi
) from a module, use the fromlist
parameter.
mod = __import__('math', fromlist=['sqrt'])
print(mod.sqrt(25))
5.0
Why Use __import__()
Instead of import
?
- Used when module names are stored in variables or come from user input
- Useful for dynamic imports in frameworks, plugins, and automation
- Helpful in meta-programming and interpreter-level operations
Example: Importing Based on User Input
module_name = input("Enter module to import: ")
mod = __import__(module_name)
print(f"Successfully imported: {mod.__name__}")
Best Practices
- For regular use, prefer the
import
statement - Use
__import__()
only when dynamic behavior is absolutely needed - Validate user input if using it to import modules dynamically
Common Mistakes
- Using it instead of
import
unnecessarily can make code harder to read - Not handling
ImportError
if the module doesn't exist
Interview Tip
This function is rarely used in interviews, but knowing it can show your depth in Python internals or dynamic programming techniques.
Summary
__import__()
dynamically imports modules in Python- Mainly used when you don’t know the module name ahead of time
- Returns a module object you can use like a normal import
Practice Problem
Write a program that takes a module name as input and tries to import it using __import__()
. If it fails, print an error message.
try:
name = input("Module name: ")
mod = __import__(name)
print(f"{name} imported successfully!")
except ImportError:
print("Module not found!")