Python Reference Library →

Python __import__() Function – Dynamic Module Import

Let’s look at __import__() function – dynamic module import

  1. Notice

    __import__() performs module importing. Ordinary import statements are usually clearer for normal application code.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
module = __import__("math")
print(module.isqrt(9))
Live state

Top-level scope

This step

__import__() performs module importing. Ordinary import statements are usually clearer for normal application code.

Picture __import__() function – dynamic module import

__import__() performs module importing. Ordinary import statements are usually clearer for normal application code.

Image brief

Alt text
A diagram for Python __import__() Function – Dynamic Module Import. Instructions: module = __import__("math") print(module.isqrt(9)). Displayed result: 3.
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python __import__() Function – Dynamic Module Import". Teaching focus: __import__() performs module importing. Ordinary import statements are usually clearer for normal application code. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS module = __import__("math") print(module.isqrt(9)) | v DISPLAYED RESULT 3 Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python __import__() Function – Dynamic Module Import. Instructions: module = __import__("math") print(module.isqrt(9)). Displayed result: 3.

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
module = __import__("math")
print(module.isqrt(9))
Live state

Top-level scope

This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
3

What do you expect this program to print?

What does this example display?

module = __import__("math")
print(module.isqrt(9))
What does this example display?
Choose one answer. You can try again.

Answer and explanation

3

Follow the printed values in order. The output is: 3

More examples and reference

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. Usually globals().
  • locals – Optional. Usually locals().
  • 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!")

What to remember

Connect what you noticed in the example with the idea below.

Remember

__import__() performs module importing. Ordinary import statements are usually clearer for normal application code.

Watch out for this idea

__import__() reads a variable from an unrelated function.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →