Objects · Lesson 15 of 18 · 16 min
Modules and context managers
import, packages, with, and cleanup you can trust.
- Import modules and packages without circular-import panic
- Write a context manager
- Use pathlib and with-open as defaults
import executes the file once
`import math` finds `math`, runs it (the first time), and binds the module object to the name `math` in your namespace. `from math import sqrt` still loads the whole module, then binds `sqrt`. Reloading is `importlib.reload`, and you almost never want it.
A package is a directory with `__init__.py` (optional in namespace packages). Relative imports (`from . import helpers`) work only inside packages. Circular imports happen when two modules need each other at import time — break the cycle by importing inside a function, or by extracting shared types to a third module.
import math
from pathlib import Path
from collections import Counter
print(math.isclose(0.1 + 0.2, 0.3))
print(Path("a/b/c.py").stem, Path("a/b/c.py").suffix)
print(Counter("book"))with is try/finally you cannot forget
`with open(path, encoding='utf-8') as f:` guarantees the file is closed. The protocol is `__enter__` (returns the value bound by `as`) and `__exit__(exc_type, exc, tb)` (cleanup; return True to swallow the exception).
`contextlib.contextmanager` lets you write that protocol as a generator: code before `yield` is enter, code after is exit. `@contextlib.closing` and `ExitStack` handle groups of resources.
from contextlib import contextmanager
@contextmanager
def banner(title):
print(f"# {title}")
try:
yield title.upper()
finally:
print("# done")
with banner("trace") as name:
print("inside", name)Check yourself
Quiz
1.`from m import x` loads:
2.`__exit__` returning True means:
3.The `as` target of `with cm() as x` is:
Practice
Exercise
Write a context manager function `capture()` using `@contextlib.contextmanager` that yields an empty list, and after the block appends 'closed' to that list. Inside the with-block, callers will append their own items.
Tutor
Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.