#contextlib — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #contextlib, aggregated by home.social.
-
Контекстные менеджеры в Python за пределами with open(): пишем свои и упрощаем код
with open() знают все. Но контекстные менеджеры в Python — это не только про файлы. Они помогают безопасно управлять соединениями с БД, транзакциями, async‑ресурсами, временными настройками и cleanup‑логикой без бесконечных try/finally. В статье разбираем, как работают контекстные менеджеры, как писать свои через contextlib и где они реально упрощают продакшен‑код.
https://habr.com/ru/companies/otus/articles/1034686/
#контекстные_менеджеры #Python #with #contextmanager #async_Python #транзакции #работа_с_БД #cleanup #contextlib #asynccontextmanager
-
Oh, this is clever.
When using pytest's mark.parametrize() to supply a list of input values and expected results to a test, some of these values might raise an exception while others don't.
Instead of having duplicate code in the test, one instance wrapped in `with pytest.raises()` and the other one without it, you can use contextlib.nullcontext to just switch out the context manager.
https://docs.pytest.org/en/8.3.x/example/parametrize.html#parametrizing-conditional-raising
-
Python context managers are a really nice way to ensure you're cleaning up after yourself.
Here I'm using https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager to make sure that every mounted directory gets unmounted at the end of the `with` block, even if there are exceptions somewhere along the way.
(Usually a context manager would yield some kind of resource. For these, it doesn't make sense, so they just have empty `yield` statements.)