Skip to main content

Use context managers with a function instead of a statement.

Project description

Use context managers with a function instead of a statement.

Provides a minimal and portable interface for using context managers with all the advantages of functions over syntax.

Allows using context managers on Python implementations that are too old or too incomplete to have the with statement.

Versioning

This library’s version numbers follow the SemVer 2.0.0 specification.

Installation

pip install with-as-a-function

Usage

Import with_, iwith, or both:

from with_ import with_, iwith

with_ wraps a function in a context manager. For example,

data = with_(open('my_file.txt'), lambda my_file: my_file.read())

is similar to:

with open('my_file.txt') as my_file:
    data = my_file.read()

iwith wraps a generator or other iterable in a context manager. For example,

lines = iwith(open('my_file.txt'), lambda my_file: my_file)

is similar to:

def _lines():
    with open('my_file.txt') as my_file:
        yield from my_file
lines = _lines()

And of course because with_ and iwith are functions, you can combine them with functools.partial and other functional programming libraries and techniques for many more uses.

Portability

Portable to all releases of Python 3, and releases of Python 2 starting with 2.2.

Even those without the with statement and without the yield from expression.

For popular Python reimplementations with quicks or bugs that make the normal implementation of this module not work, other implementations are included in the source distribution.

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

with-as-a-function-1.1.0.tar.gz (8.1 kB view hashes)

Uploaded Source

Built Distributions

with_as_a_function-1.1.0-py33-none-any.whl (3.5 kB view hashes)

Uploaded Python 3.3

with_as_a_function-1.1.0-py26.py30-none-any.whl (3.8 kB view hashes)

Uploaded Python 2.6 Python 3.0

with_as_a_function-1.1.0-py25-none-any.whl (3.9 kB view hashes)

Uploaded Python 2.5

with_as_a_function-1.1.0-py22-none-any.whl (4.3 kB view hashes)

Uploaded Python 2.2

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