import — Intermediate Playground
Loads a module or package into the current namespace
Python Playground
# 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())
Output
Click "Run" to execute your code
Use aliases for long module names. Conditional imports provide fallbacks. Function-scope imports delay loading until needed.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?