Skip to main content

Conditionally enter a context manager

Project description

Package Contents

conditional(condition, contextmanager)

Enter contextmanager only if condition is true.


The conditional context manager comes handy when you always want to execute a with-block but only conditionally want to apply its context manager.

If you find yourself writing code like this:


Consider replacing it with:

with conditional(CONDITION, CONTEXTMANAGER()):


The context manager ships with type annotations. Type checkers and IDEs can use this information to implement type safety and auto completion.


Say we want to ignore signals when a pager application is in the foreground, but not otherwise:

from conditional import conditional

with conditional(has_pager(cmd), ignoresignals()):


For further details please refer to the API Documentation.


1.5 - 2023-09-14

  • Add type annotations to the context manager. [stefan]

  • Update tox.ini for latest tox. [stefan]

  • Add GitHub CI workflow. [stefan]

  • Add .readthedocs.yaml file. [stefan]

  • Pin sphinx and sphinx-rtd-theme versions in docs extra. [stefan]

  • Add mypy extra which installs mypy. [stefan]

1.4 - 2022-03-09

  • Add Python 3.8-3.10 to tox.ini. Remove old Python versions. [stefan]

  • Replace deprecated python test in tox.ini. [stefan]

  • Remove deprecated test_suite and tests_require from [stefan]

  • Move metadata to setup.cfg and add a pyproject.toml file. [stefan]

  • Include tests in sdist but not in wheel. [stefan]

1.3 - 2019-01-28

  • Add [stefan]

  • Release as wheel. [stefan]

1.2 - 2017-02-05

  • Support Python 2.6-3.6 without 2to3. [stefan]

  • Add a LICENSE file. [stefan]

1.1 - 2014-04-19

  • Remove setuptools from install_requires because it isn’t. [stefan]

1.0 - 2012-05-16

  • Initial release. [stefan]

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

conditional-1.5.tar.gz (7.4 kB view hashes)

Uploaded source

Built Distribution

conditional-1.5-py2.py3-none-any.whl (4.6 kB view hashes)

Uploaded py2 py3

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