Yandex

Python __import__() Function – Dynamic Module Import



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:

  • nameRequired. The name of the module to import (as a string).
  • globalsOptional. Usually globals().
  • localsOptional. Usually locals().
  • fromlistOptional. A list of names to import from the module.
  • levelOptional. 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!")


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M