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 manager is:
class Indenter:
def __init__(self):
self.level = 0
def __enter__(self):
self.level += 1
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.level -= 1
def print(self, text):
print(' ' * self.level + text)
with Indenter() as indent:
indent.print('hi')
with indent:
indent.print('hello!')
with indent:
indent.print('bonjour')
I wonder if it is possible to implement the same solution in the generator-based context manager? The solutions I tried did not work, probably because I just did not grasp the idea of context managers...
UPDATE:
Here's my approach with printing function onboard, so the context yields this function. It is better, but still works only with single indentation:
from contextlib import contextmanager
@contextmanager
def indenter():
level = 0
def prints(text):
print('____' * level + text)
try:
level += 1
yield prints
finally:
level -= 1
with indenter() as ind:
ind('aaaa')
with ind:
ind('bbbbb')
____aaaa
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
29 with indenter() as ind:
30 ind('aaaa')
---> 31 with ind:
32 ind('bbbbb')
AttributeError: __enter__
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…