Skip to main content

Context managers. Initially just `stackattrs`.

Project description

Latest release 20200228.1: Initial release with stackattrs context manager.

Context managers. Initially just stackattrs.

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.

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'

Release Log

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-20200228.1.tar.gz (2.9 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