utils.tools.ContextWrapper¶
Class · Context · Source
inst_wctx = mdnc.utils.tools.ContextWrapper(
instance, exit_method=None
)
A simple wrapper for adding context support to some special classes.
Example
For example, there is an instance f, it defines f.close(), but does not support the context. In this case, we could use this wrapper to add context support:
1 2 3 4 5 6 |
|
Tip
Actually, the standard lib has already provided a tool with the similar usage. See contextlib.closing for viewing the details.
In most cases, we recommend to use the solution from the contextlib
. However, if an instance implements an exiting function not named close()
, then we have to use this class.
Arguments¶
Requries
Argument | Type | Description |
---|---|---|
instance | object | An instance requring the context support. |
exit_method | object | A callable object (function), if not provided, would call the instance.close() method during the exiting stage. If provided, would call exit_method(instance) instead. |
Operators¶
__enter__
, __exit__
¶
with mdnc.utils.tools.ContextWrapper(instance, exit_method=None) as inst_wctx:
...
Work with the context. When leaving the context for any reason (sucessfully running all codes or meeting any exceptions), the exit_method
would be called.
Examples¶
Example
1 2 3 4 5 6 7 8 9 |
|
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 62.98it/s]
Last update: March 14, 2021