Python 3.8+astfunction
ast.get_source_segment()
helper functions
Returns the piece of source text a node came from. Lets you show a student the exact fragment of their code rather than an unparse reconstruction.
Syntax
ast.get_source_segment(source, node, *, padded=False)
You need the same source text that went into parse: positions refer to it. For a node without positions (built by hand) it returns None rather than raising. A multi-line statement comes back without the first line's indentation; padded=True pads it with spaces to the original column. Added in 3.8.
Examples
import ast
src = 'total = price * qty'
node = ast.parse(src).body[0].value
print(ast.get_source_segment(src, node)) # → price * qty
print(ast.unparse(node)) # → price * qty
print(ast.get_source_segment(src, ast.Name(id='x'))) # → None
See also
Open in the full glossarydocs.python.orgReport an inaccuracy