![]() | Ned Batchelder : Blog | Code | Text | Site Line continuations from tokenize.generate_tokens » Home : Blog : September 2009 |
OK, this is really geeky, but I wish I had found it on the interwebs, so I'm putting it here for the next guy. tokenize.generate_tokens is a very useful function in the Python standard library: it tokenizes Python source code, generating a stream of tokens. I used it to add syntax coloring to the HTML reporting in coverage.py. But it has a flaw, which the docs hint at:
If you've continued a source line with a backslash: def my_function(arguments): then generate_tokens doesn't ever give you a token with that backslash as the text. If you're trying to recreate the Python source from the tokens, the backslashes will be missing. Googling this problem turns up some muttering about how something ought to be done about it, but no solutions. It turned out not to be too hard to wrap the token generator to insert the needed backslashes: def phys_tokens(toks): Use it by passing it the generate_tokens generator: tokgen = tokenize.generate_tokens(source_file.readline)
tagged:
python» react | |
Comments
Add a comment: