Skip to main content

Compose context managers from a sequence

Project description

context_compose

Python utility library to compose context managers (3.6+)

Motivation

When you want to use a dynamic combination of context managers together, and the builtin ways are too ugly or inflexible.

Turn this:

import os

if __name__ == "__main__":
    if os.environ.get("DEBUG") and os.environ.get("PROFILE":
        with debugger(), profile():
            main()
    elif os.environ.get("DEBUG"):
        with debugger():
            main()
    elif os.environ.get("DEBUG"):
        with debugger():
            main()

Into this:

import os

from context_compose import compose, impotent_manager


if __name__ == "__main__":
    managers = [
        debugger() if os.environ.get("DEBUG") else impotent_manager(),
        profile() if os.environ.get("PROFILE") else impotent_manager(),
    ]
    with compose(managers):
        main()

impotent_manager is a useful substitute when your code has a with block, you'd rather keep to a single pattern so a context manager must be provided to it.

How it works

Under the hood it uses contextlib.ExitStack to layer context managers in list order.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

context-compose-0.0.2.tar.gz (2.1 kB view hashes)

Uploaded Source

Built Distribution

context_compose-0.0.2-py3-none-any.whl (3.1 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page