-
-
Save jab/bac1d7991493f49d99e41d2c2db177fd to your computer and use it in GitHub Desktop.
Indentation context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import functools | |
import contextlib | |
@contextlib.contextmanager | |
def indented_output(indent=4, space=chr(32)): | |
""" Precede each carriage return with some quantity of spaces. | |
While nesting `indented_output` contexts, be prepared | |
that if a line does not begin with a line feed character, | |
it shall print with unchanged indentation. | |
To keep the indentation as expected, | |
print last line feed character of a parent block | |
in the beginning of a child block. | |
""" | |
try: | |
original_stderr_write = sys.stderr.write | |
original_stdout_write = sys.stdout.write | |
def write_indented(write_call, data): | |
write_call.__call__( | |
data.replace('\n', '\n' + (space * indent))) | |
sys.stderr.write = functools.partial( | |
write_indented, original_stderr_write) | |
sys.stdout.write = functools.partial( | |
write_indented, original_stdout_write) | |
yield | |
finally: | |
sys.stderr.write = original_stderr_write | |
sys.stdout.write = original_stdout_write |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment