Skip to main content

Assorted context managers.

Project description

Assorted context managers.

Latest release 20210420: Docstring corrections and improvements.

Function popattrs(o, attr_names, old_values)

The "pop" part of stackattrs. Restore previous attributes of o named by attr_names with previous state in old_values.

This can be useful in hooks/signals/callbacks, where you cannot inline a context manager.

Function popkeys(d, key_names, old_values)

The "pop" part of stackkeys. Restore previous key values of d named by key_names with previous state in old_values.

This can be useful in hooks/signals/callbacks, where you cannot inline a context manager.

Function pushattrs(o, **attr_values)

The "push" part of stackattrs. Push attr_values onto o as attributes, return the previous attribute values in a dict.

This can be useful in hooks/signals/callbacks, where you cannot inline a context manager.

Function pushkeys(d, **key_values)

The "push" part of stackkeys. Push key_values onto d as key values. return the previous key values in a dict.

This can be useful in hooks/signals/callbacks, where you cannot inline a context manager.

Function setup_cmgr(cmgr)

Run the set up phase of the context manager cmgr and return a callable which runs the tear down phase.

This is a convenience wrapper for the lower level twostep() function which produces a two iteration generator from a context manager.

The purpose of setup_cmgr() is to split any context manager's operation across two steps when the set up and teardown phases must operate in different parts of your code. A common situation is the __enter__ and __exit__ methods of another context manager class.

The call to setup_cmgr() performs the "enter" phase and returns the tear down callable. Calling that performs the tear down phase.

Example use in a class:

class SomeClass:
    def __init__(self, foo)
        self.foo = foo
        self._teardown = None
    def __enter__(self):
        self._teardown = setup_cmgr(stackattrs(o, setting=foo))
    def __exit__(self, *_):
        self._teardown()
        self._teardown = None

Class StackableState(_thread._local)

An object which can be called as a context manager to push changes to its attributes.

Example:

>>> state = StackableState(a=1, b=2)
>>> state.a
1
>>> state.b
2
>>> state
StackableState(a=1,b=2)
>>> with state(a=3, x=4):
...     print(state)
...     print("a", state.a)
...     print("b", state.b)
...     print("x", state.x)
...
StackableState(a=3,b=2,x=4)
a 3
b 2
x 4
>>> state.a
1
>>> state
StackableState(a=1,b=2)

Method StackableState.__call__(self, **kw)

Calling an instance is a context manager yielding self with attributes modified by kw.

Function stackattrs(o, **attr_values)

Context manager to push new values for the attributes of o and to restore them afterward. Returns a dict containing a mapping of the previous attribute values. Attributes not present are not present in the mapping.

Restoration includes deleting attributes which were not present initially.

This makes it easy to adjust temporarily some shared context object without having to pass it through the call stack.

See stackkeys for a flavour of this for mappings.

Example of fiddling a programme's "verbose" mode:

>>> class RunModes:
...     def __init__(self, verbose=False):
...         self.verbose = verbose
...
>>> runmode = RunModes()
>>> if runmode.verbose:
...     print("suppressed message")
...
>>> with stackattrs(runmode, verbose=True):
...     if runmode.verbose:
...         print("revealed message")
...
revealed message
>>> if runmode.verbose:
...     print("another suppressed message")
...

Example exhibiting restoration of absent attributes:

>>> class O:
...     def __init__(self):
...         self.a = 1
...
>>> o = O()
>>> print(o.a)
1
>>> print(o.b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'O' object has no attribute 'b'
>>> with stackattrs(o, a=3, b=4):
...     print(o.a)
...     print(o.b)
...     o.b = 5
...     print(o.b)
...     delattr(o, 'a')
...
3
4
5
>>> print(o.a)
1
>>> print(o.b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'O' object has no attribute 'b'

Function stackkeys(d, **key_values)

Context manager to push new values for the key values of d and to restore them afterward. Returns a dict containing a mapping of the previous key values. Keys not present are not present in the mapping.

Restoration includes deleting key values which were not present initially.

This makes it easy to adjust temporarily some shared context object without having to pass it through the call stack.

See stackattrs for a flavour of this for object attributes.

Example of making log entries which may reference some higher level context log entry:

>>> import time
>>> global_context = {
...     'parent': None,
... }
>>> def log_entry(desc, **kw):
...     print("log_entry: global_context =", repr(global_context))
...     entry = dict(global_context)
...     entry.update(desc=desc, when=time.time())
...     entry.update(kw)
...     return entry
...
>>> log_entry("stand alone entry")    #doctest: +ELLIPSIS
log_entry: global_context = {'parent': None}
{'parent': None, 'desc': 'stand alone entry', 'when': ...}
>>> context_entry = log_entry("high level entry")
log_entry: global_context = {'parent': None}
>>> context_entry                     #doctest: +ELLIPSIS
{'parent': None, 'desc': 'high level entry', 'when': ...}
>>> with stackkeys(global_context, parent=context_entry): #doctest: +ELLIPSIS
...     print(repr(log_entry("low level event")))
...
log_entry: global_context = {'parent': {'parent': None, 'desc': 'high level entry', 'when': ...}}
{'parent': {'parent': None, 'desc': 'high level entry', 'when': ...}, 'desc': 'low level event', 'when': ...}
>>> log_entry("another standalone entry")    #doctest: +ELLIPSIS
log_entry: global_context = {'parent': None}
{'parent': None, 'desc': 'another standalone entry', 'when': ...}

Function twostep(cmgr)

Return a generator which operates the context manager cmgr.

See also the setup_cmgr(cmgr) function which is a convenience wrapper for this low level generator.

The purpose of twostep() is to split any context manager's operation across two steps when the set up and teardown phases must operate in different parts of your code. A common situation is the __enter__ and __exit__ methods of another context manager class.

The first iteration performs the "enter" phase and yields. The second iteration performs the "exit" phase and yields.

Example use in a class:

class SomeClass:
    def __init__(self, foo)
        self.foo = foo
        self._cmgr = None
    def __enter__(self):
        self._cmgr = next(stackattrs(o, setting=foo))
    def __exit__(self, *_):
        next(self._cmgr)
        self._cmgr = None

Release Log

Release 20210420: Docstring corrections and improvements.

Release 20210306:

  • New twostep() and setup_cmgr() functions to split a context manager into set up and teardown phases for when these must occur in different parts of the code.
  • New thread local StackableState class which can be called to push attribute changes with stackattrs - intended for use as shared global state to avoiod passing through deep function call chains.

Release 20200725.1: Docstring improvements.

Release 20200725: New stackkeys and components pushkeys and popkeys doing "stackattrs for dicts/mappings".

Release 20200517:

  • Add nullcontext like the one from recent contextlib.
  • stackattrs: expose the push and pop parts as pushattrs() and popattrs().

Release 20200228.1: Initial release with stackattrs context manager.

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

cs.context-20210420.tar.gz (7.5 kB view details)

Uploaded Source

File details

Details for the file cs.context-20210420.tar.gz.

File metadata

  • Download URL: cs.context-20210420.tar.gz
  • Upload date:
  • Size: 7.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/49.2.1 requests-toolbelt/0.9.1 tqdm/4.55.0 CPython/3.9.2

File hashes

Hashes for cs.context-20210420.tar.gz
Algorithm Hash digest
SHA256 29c7054309a31d03566b3da203fe052b91b5ffa2bee3bdade91447a4349247cb
MD5 a08bd1cb16d93e5760501c4cb223b958
BLAKE2b-256 603a5acc487e1ec11598c970e9042b389c3533db7edef347685220de2cd2648c

See more details on using hashes here.

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