patternpythonModeratepending
Python context managers for resource cleanup
Viewed 0 times
context managerwith statementcontextlibresource leak__enter____exit__
terminallinuxmacos
Problem
Resources like files, database connections, locks, and network sockets are not being properly closed, leading to resource leaks, locked files, or exhausted connection pools.
Solution
Always use context managers (with statement) for resources that need cleanup. (1) Files: with open('file.txt') as f: — auto-closes even if exception occurs. (2) Custom context manager with contextlib: @contextmanager def managed_resource(): resource = acquire(); try: yield resource; finally: release(resource). (3) Database: with conn.cursor() as cur: — auto-commits/rollbacks. (4) For multiple resources: with open('a') as f1, open('b') as f2:. (5) Async: async with aiohttp.ClientSession() as session:. (6) Never use try/finally for resource cleanup when a context manager is available.
Why
Context managers guarantee cleanup via __exit__ even when exceptions occur. Manual try/finally is error-prone — developers forget to add it, or add it but miss edge cases.
Revisions (0)
No revisions yet.