Getting at line numbers with parsermodule

Tim Peters tim_one at email.msn.com
Tue Aug 10 23:23:47 EDT 1999


[Charles G Waldman]
> ...
> I'm trying to use the parser module.
> ...
> I have trouble printing out the line number in the source where
> the offending code occurred.

RTFM for this one:  ast2list and ast2tuple each take an optional line_info
argument, defaulting to false.

> I tried to simply go throught the AST object (converted to a tuple) and
> look for NEWLINE tokens, count these as I go throught the AST to get a
> current line-count.  This doesn't seem to work correctly since there are
> fewer NEWLINE tokens than there were lines in the original file.

Right, a NEWLINE in Python's grammar occurs at the end of a statement, and
not every physical \n ends a statement.  For example, you won't get NEWLINE
at the end of any line that's continued (via string, backslash, or
open-brace/bracket/paren continuation).  So far as Python's parsing is
concerned the statement hasn't ended yet.

> What I'd like to be able to do is, given any node in an AST object
> returned by compile.suite, is to know the line number in the input
> that corresponds to this node.  Is this doable?

No.  Specifying a true line_info argument will get you line numbers for
terminal tokens, though.

would-the-manual-lie?-ly y'rs  - tim






More information about the Python-list mailing list