Created
August 26, 2010 19:10
-
-
Save kergoth/552007 to your computer and use it in GitHub Desktop.
Remove a level of indentation from python code
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
from tokenize import generate_tokens, untokenize, INDENT, DEDENT | |
def dedent_python(codestr): | |
"""Remove the first level of indentation from a block of python code""" | |
indent = None | |
level = 0 | |
tokens = [] | |
lines = codestr.splitlines(True) | |
for toknum, tokval, _, _, _ in generate_tokens(iter(lines).next): | |
if toknum == INDENT: | |
level += 1 | |
if level == 1: | |
indent = tokval | |
continue | |
else: | |
tokval = level * indent | |
elif toknum == DEDENT: | |
level -= 1 | |
if level == 0: | |
continue | |
tokens.append((toknum, tokval)) | |
return untokenize(tokens) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment