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