Julien Danjou 11/4/2019

Finding definitions from a source file and a line number in Python

Read Original

This article details a Python programming challenge: determining the enclosing function, method, or class for a given line number in a source file. It explains why simple parsing is insufficient and presents a robust solution using Python's `ast` and `tokenize` modules to correctly handle file encoding and traverse the Abstract Syntax Tree to find the closest definition.

Finding definitions from a source file and a line number in Python

Comments

No comments yet

Be the first to share your thoughts!

Browser Extension

Get instant access to AllDevBlogs from your browser

Top of the Week

1
Quoting Thariq Shihipar
Simon Willison 2 votes
2
The Beautiful Web
Jens Oliver Meiert 1 votes
3
Container queries are rad AF!
Chris Ferdinandi 1 votes
4
Top picks — 2026 January
Paweł Grzybek 1 votes
5
In Praise of –dry-run
Henrik Warne 1 votes
7
Vibe coding your first iOS app
William Denniss 1 votes