|
|
|
|
|
by tzot
1378 days ago
|
|
There's `contextlib.closing` for objects that do not support the context manager protocol and they should be closed. And then one can simulate defer in the spirit of the `atexit` module with a single context manager (say `finalizer`), defined only once, which could be used as: with finalizer() as defer:
...
req = requests.get('https://w3.org/')
defer(req.close) # just like contextlib.closing
...
a_dict['key'] = value
defer(a_dict.__delitem__, 'key')
...
defer(print, "all defers ran", file=sys.stderr)
...
The `__call__` of finalizer adds callables with their *args and **kwargs to a fifo or a stack, and its `__exit__` will call them in sequence. |
|