import — Advanced Examples
Loads a module or package into the current namespace
Dynamic imports and importlib
Importing modules programmatically at runtime.
python
import importlib # Import a module by name string mod_name = "json" mod = importlib.import_module(mod_name) print(mod.dumps({"dynamic": True})) # Reload a module importlib.reload(mod) # Check if a module is available def is_available(name): try: importlib.import_module(name) return True except ImportError: return False for pkg in ["json", "numpy", "nonexistent_pkg"]: print(f"{pkg}: {is_available(pkg)}")
importlib lets you import modules by string name, which is useful for plugin systems and optional dependencies.
Want to try these examples interactively?
Open Advanced Playground