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 availabledefis_available(name):
try:
importlib.import_module(name)
returnTrueexcept ImportError:
returnFalsefor pkg in ["json", "numpy", "nonexistent_pkg"]:
print(f"{pkg}: {is_available(pkg)}")
Output
Click "Run" to execute your code
importlib lets you import modules by string name, which is useful for plugin systems and optional dependencies.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?