This documentation covers IPython versions 6.0 and higher. Beginning with version 6.0, IPython stopped supporting compatibility with Python versions lower than 3.3 including all versions of Python 2.7.

If you are looking for an IPython version compatible with Python 2.7, please use the IPython 5.x LTS release and refer to its documentation (LTS is the long term support release).

Module: utils.contexts

Miscellaneous context managers.

1 Class

class IPython.utils.contexts.preserve_keys(dictionary, *keys)

Bases: object

Preserve a set of keys in a dictionary.

Upon entering the context manager the current values of the keys will be saved. Upon exiting, the dictionary will be updated to restore the original value of the preserved keys. Preserved keys which did not exist when entering the context manager will be deleted.


>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> with preserve_keys(d, 'b', 'c', 'd'):
...     del d['a']
...     del d['b']      # will be reset to 2
...     d['c'] = None   # will be reset to 3
...     d['d'] = 4      # will be deleted
...     d['e'] = 5
...     print(sorted(d.items()))
[('c', None), ('d', 4), ('e', 5)]
>>> print(sorted(d.items()))
[('b', 2), ('c', 3), ('e', 5)]
__init__(dictionary, *keys)