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?
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 likelib2to3or usetokenize(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).