import — Intermediate Examples
Loads a module or package into the current namespace
Import patterns and aliasing
Different ways to import and organize imports.
python
# Import specific items from math import pi, sqrt, ceil # Import with alias import datetime as dt now = dt.datetime.now() print(f"Now: {now}") # Conditional imports try: import ujson as json except ImportError: import json data = json.dumps({"key": "value"}) print(data) # Import in function scope (lazy loading) def heavy_computation(): import statistics return statistics.mean([1, 2, 3, 4, 5]) print(heavy_computation())
Use aliases for long module names. Conditional imports provide fallbacks. Function-scope imports delay loading until needed.
Want to try these examples interactively?
Open Intermediate Playground