Skip to content

Instantly share code, notes, and snippets.

@kergoth
Created August 26, 2010 19:10
Show Gist options
  • Save kergoth/552007 to your computer and use it in GitHub Desktop.
Save kergoth/552007 to your computer and use it in GitHub Desktop.
Remove a level of indentation from python code
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