Skip to main content

Conditionally enter a context manager

Project description

Package Contents

conditional(condition, contextmanager)

Enter contextmanager only if condition is true.

Overview

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:

if CONDITION:
    with CONTEXTMANAGER():
        BODY()
else:
    BODY()

Consider replacing it with:

with conditional(CONDITION, CONTEXTMANAGER()):
    BODY()

Examples

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()):
    os.system(cmd)

Changelog

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.2.zip (13.7 kB view hashes)

Uploaded Source

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