Skip to content Skip to sidebar Skip to footer

Class-based Context Manager Vs Generator-based One

There's an Indenter() class we could use to have text indentations levels like this: hi! hello bonjour The class-based implementation of the context manage

Solution 1:

I came up with this. It can be used in a similar way as your class version (but not exactly the same).

from contextlib import contextmanager

defindenter():
    level = 0defprints(text):
        print('____' * level + text)

    @contextmanagerdefind():
        nonlocal level
        try:
            level += 1yield prints
        finally:
            level -= 1return ind


ind = indenter()
with ind() as prints:
    prints('aaa')
    with ind() as prints:
        prints('bbb')
        with ind() as prints:
            prints('ccc')

Output:

____aaa
________bbb
____________ccc

Post a Comment for "Class-based Context Manager Vs Generator-based One"