Skip to content

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
import mdnc
f = create_f(...)
with mdnc.utils.tools.ContextWrapper(f) as fc:
    do some thing ...
# When leaving the context, the f.close() method would be called
# automatically.
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
import time
import tqdm
import mdnc

num_iters = 100
with mdnc.utils.tools.ContextWrapper(tqdm.tqdm(total=num_iters)) as tq:
    for i in range(num_iters):
        tq.update(1)
        time.sleep(0.001)
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:01<00:00, 62.98it/s]

Last update: March 14, 2021

Comments