__import__() Low-level import
Last updated: 2026-09-22
__import__() Low-level import
__import__ is the low-level function behind the import statement; prefer the import statement unless you need dynamic imports.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
__import__(name, globals=None, locals=None, fromlist=(), level=0)
⚙️ Parameters
| name Required | The module name (string). |
|---|---|
| globals Optional | The global namespace dict.(Default:None) |
| locals Optional | The local namespace dict.(Default:None) |
| fromlist Optional | Names of submodules or attributes to import.(Default:()) |
| level Optional | Relative import level; 0 means absolute.(Default:0) |
Returns:The top-level module object (not the attributes in fromlist).
💥 Raises
ImportError— Raised when the module cannot be found or imported.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
4.0
⚠️ Warning Dynamic loading of untrusted module names is a security risk; use `import` for ordinary cases.
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhy not call __import__() directly instead of using the import statement?
AThe import statement handles name binding, fromlist semantics, and other details; __import__() is just a low-level implementation function — use import for everyday importing.
QWhat does __import__('math') return?
AIt returns the math module object. Note that it returns the top-level module: for import a.b, __import__ returns a rather than b.
QWhat should I use for dynamic imports?
APrefer importlib.import_module(name); it returns the specified module rather than the top-level one, giving clearer semantics than __import__.
QIs dynamically importing an untrusted module name risky?
AYes — it may load and execute arbitrary code; when the module name comes from user input, strictly validate it against a whitelist.