How can I parse source code string src_string to get blocks of executable strings?
I'd like the process to be reversible (i.e. assert src_string == '\n'.join(blocks)), so comments and blanks are should be conserved (they are executable!).
Note: I'm not talking about how to get source code of function here.
I was thinking of using ast to parse the code, get the s.lineno, s.end_lineno of each s ast.walk would give me, and use that information to structure src_code.splitlines() (getting both blocks and comments etc.).
But I'm thinking this must exist already, somewhere. (Debuggers manage to provide us with the ability to step through executable code (while still seeing the original string).)
Example:
src_string = """from inspect import signature
# Just wrapping the func gives you a sort of copy of the func.
wrapped_func = wrap(func) # no transformations
assert (
wrapped_func(2, 'co')
== 'coco'
== func(2, 'co')
)
assert str(signature(wrapped_func)) == \
"(a, b: str, c='hi')" # "(a, b: str, c='hi')"
"""
blocks = [
"from inspect import signature",
"",
"# Just wrapping the func gives you a sort of copy of the func.",
"wrapped_func = wrap(func) # no transformations",
"""assert (
wrapped_func(2, 'co')
== 'coco'
== func(2, 'co')
)""",
"""assert str(signature(wrapped_func)) == \
"(a, b: str, c='hi')" # "(a, b: str, c='hi')"
"""
]
assert '\n'.join(blocks) == src_string
def is_valid_python_code(code_str):
try:
ast.parse(code_str)
return True
except SyntaxError:
return False
assert all(map(is_valid_python_code, blocks))