Context Manager Resource Lifecycle
Wrap acquire and release in a contextmanager generator so exceptions still trigger cleanup and timing or locking boilerplate disappears.
Code
import time
from contextlib import contextmanager
@contextmanager
def timed_section(label: str):
"""计时上下文:无论成功或异常都输出耗时。"""
start = time.perf_counter()
try:
yield label
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed * 1000:.1f}ms")
@contextmanager
def pooled_connection(pool: list, label: str):
"""借还式资源管理:异常时也会归还连接。"""
if not pool:
raise RuntimeError("pool exhausted")
conn = pool.pop()
try:
yield conn
finally:
pool.append(conn) # finally 保证归还,等价于 try/finally 样板
with timed_section("batch"):
pool = ["conn-1", "conn-2"]
with pooled_connection(pool, "job-a") as conn:
print("using", conn)
time.sleep(0.01)
print("pool after:", pool)Output
Captured from a sandboxed run of this snippet in the build pipeline.
using conn-2
pool after: ['conn-1', 'conn-2']
batch: 10.2msHow the snippet works
Context Manager Resource Lifecycle is built around the functions timed_section and pooled_connection.
Failure is loud: RuntimeError aborts the current operation instead of degrading it.
The input pool is mutated in place — callers that need the original must pass a copy.
What to watch for
- The guard
not poolshort-circuits the flow with an earlyraisewhen its condition holds. poolis mutated in place — the value you pass will not be the same afterward.
Applying it
The main signature reads def timed_section(label: str)
Running the file prints labeled results such as using, pool after: — each operation’s effect is visible in the output.
Import timed_section from the file and call it — the rest of the code is implementation detail.
Statements that matter
def pooled_connection(pool: list, label: str):
"""借还式资源管理:异常时也会归还连接。"""
if not pool:
raise RuntimeError("pool exhausted")
conn = pool.pop()
try:
yield conn
finally:
pool.append(conn) # finally 保证归还,等价于 try/finally 样板
with pooled_connection(pool, "job-a") as conn:
print("using", conn)
time.sleep(0.01)
def timed_section(label: str):
"""计时上下文:无论成功或异常都输出耗时。"""
start = time.perf_counter()
try:
yield label
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed * 1000:.1f}ms")
Interactive Tools for This Topic
FAQ
- Does `timed_section` modify its input?
- Yes — `pool` is mutated in place. Pass a copy if the caller needs the original preserved.
- How does the code behave when input is bad?
- Validation comes first — `RuntimeError` marks the failure at `not pool`, before any partial work happens.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `time`, `contextlib`. The file defines `timed_section`, `pooled_connection` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.