2

In python 3.8 while doing ast.parse you get a end_lineno variable:

import ast

code_example = 'from typing import List, Dict'
parsed_tree = ast.parse(code_example)

for item in parsed_tree.body:
    print(item.__dict__)

Results in:

{
'module': 'typing', 
'names': [<ast.alias object at 0x7fac49c1d2b0>, <ast.alias object at 0x7fac49c1d5e0>], 
'level': 0, 
'lineno': 1, 
'col_offset': 0, 
'end_lineno': 1, 
'end_col_offset': 29
}

In python3.7 the end_lineno (and end_col_offset) variables aren't there, how do you get manually?

ArcLight_Slavik
  • 113
  • 1
  • 10
  • Does this answer your question? [How to get lineno of "end-of-statement" in Python ast](https://stackoverflow.com/questions/39779538/how-to-get-lineno-of-end-of-statement-in-python-ast) – python_user May 16 '21 at 03:38
  • The answer uses tokenize and I need to work with the result of ast.parse if possible. – ArcLight_Slavik May 16 '21 at 04:36

1 Answers1

0

In python3.7 the end_lineno (and end_col_offset) variables aren't there, how do you get manually?

There is no standard way of retrieving them in older versions, since this is highly coupled with the parser (not the parser actually, but for 3.8/3.9 it was done in the ast.c (CST -> AST conversion code). What you can do is either use something like lib2to3 or use tokenize (tokenize the source from the start of the import statement to the start of the next statement and find the non-whitespace non-comment last token).