1def indent(func):
2 """
3 Decorator for allowing to use method as normal method or with
4 context manager for auto-indenting code blocks.
5 """
6 def wrapper(self, line, *args, optimize=True, **kwds):
7 last_line = self._indent_last_line
8 line = func(self, line, *args, **kwds)
9 # When two blocks have the same condition (such as value has to be dict),
10 # do the check only once and keep it under one block.
11 if optimize and last_line == line:
12 self._code.pop()
13 self._indent_last_line = line
14 return Indent(self, line)
15 return wrapper
16
17
18class Indent:
19 def __init__(self, instance, line):
20 self.instance = instance
21 self.line = line
22
23 def __enter__(self):
24 self.instance._indent += 1
25
26 def __exit__(self, type_, value, traceback):
27 self.instance._indent -= 1
28 self.instance._indent_last_line = self.line