Getting at line numbers with parsermodule

Fred L. Drake, Jr. fdrake at acm.org
Tue Aug 10 17:54:04 EDT 1999


Charles G Waldman writes:
 > 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?  Any suggestions?

Charles,
  To get at the nodes, you're using either the totuple() or tolist()
methods of the AST objects (or ast2tuple(), ast2list()).  There is an
optional parameter which may be set to true (1 works nicely) to get
line numbers for each terminal token.  One issue: the numbers are
those stored in the "struct node" structure, which is the line number
of the end of token.  Getting the line number of the token start is
simple:

>>> import parser, pprint, string
>>> ast = parser.expr('"""foo\nbar"""')
>>> pprint(ast.totuple(1))
(258,
 (308,
  (288,
   (289,
    (290,
     (291,
      (293,
       (294,
        (295,
         (296,
          (297,
           (298, (299, (300, (301, (3, '"""foo\012bar"""', 2))))))))))))))),
 (4, '', 2),
 (0, '', 2))
>>> #                                this is bolluxed -----^
... 2 - string.count('"""foo\nar"""', '\n')
1
>>> 

  I hope this helps!


  -Fred

--
Fred L. Drake, Jr.	     <fdrake at acm.org>
Corporation for National Research Initiatives




More information about the Python-list mailing list