home.social

#contextlib — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #contextlib, aggregated by home.social.

fetched live
  1. Контекстные менеджеры в Python за пределами with open(): пишем свои и упрощаем код

    with open() знают все. Но контекстные менеджеры в Python — это не только про файлы. Они помогают безопасно управлять соединениями с БД, транзакциями, async‑ресурсами, временными настройками и cleanup‑логикой без бесконечных try/finally. В статье разбираем, как работают контекстные менеджеры, как писать свои через contextlib и где они реально упрощают продакшен‑код.

    habr.com/ru/companies/otus/art

    #контекстные_менеджеры #Python #with #contextmanager #async_Python #транзакции #работа_с_БД #cleanup #contextlib #asynccontextmanager

  2. 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.

    docs.pytest.org/en/8.3.x/examp

    #Python #pytest #contextlib

  3. Python context managers are a really nice way to ensure you're cleaning up after yourself.

    Here I'm using docs.python.org/3/library/cont 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.)

    #Python #contextlib #contextmanager #mount