Skip to content

Instantly share code, notes, and snippets.

@podhmo
Last active July 13, 2019 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podhmo/739dcdb815e78db6e912c532717141d8 to your computer and use it in GitHub Desktop.
Save podhmo/739dcdb815e78db6e912c532717141d8 to your computer and use it in GitHub Desktop.
lineno:4 code:return "[]" node:Node(simple_stmt, [Node(return_stmt, [Leaf(1, 'return'), Leaf(3, '"[]"')]), Leaf(4, '\n')])
from pycomment.parse import parse_file, node_name, PyTreeVisitor, token
class Visitor(PyTreeVisitor):
def __init__(self, lineno):
self.lineno = lineno
self.r = []
# todo: performance
def visit(self, node):
if node.get_lineno() == self.lineno and node.type != token.INDENT:
self.r.append(node)
return
super().visit(node)
def run(filename: str, *, lineno: int) -> None:
visitor = Visitor(lineno)
t = parse_file(filename)
visitor.visit(t)
node = next(iter(visitor.r))
print(f"lineno:{node.get_lineno()} code:{str(node).rstrip()} node:{node!r}")
filename = "target00.py"
run(filename, lineno=4)
class A:
def f(self, x):
if x is None:
return "[]"
else:
return f"[{x}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment