indent.py 920 B

12345678910111213141516171819202122232425262728
  1. def 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. class Indent:
  17. def __init__(self, instance, line):
  18. self.instance = instance
  19. self.line = line
  20. def __enter__(self):
  21. self.instance._indent += 1
  22. def __exit__(self, type_, value, traceback):
  23. self.instance._indent -= 1
  24. self.instance._indent_last_line = self.line