Aurélien Tronc
Aurélien Tronc

Reputation: 49

Get line n° of an instruction

I am writting a code and i already know i'll have to change some instructions when i'll have more information. I already know the specific lines i'll have to change, but since the code is a bit long, i'd like to prepare the moment i'll have to change those lines, by printing the n° of those lines. Actually i'd like something like a this_line() function that would work like this :

1 
2 
3 print('this line is the n°'.format(this_line())
4

>>> this line is the n°3

Can i do this without converting my code in .txt and counting the lines ?

Upvotes: 0

Views: 190

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155458

The inspect module has you covered. Just import inspect, and run:

inspect.currentframe().f_lineno

to get the line number of the currently executing frame.

Note, this is a feature specific to CPython (the reference interpreter), per the docs:

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

I'm unclear on whether the concept of a frame and its line number will exist elsewhere, but this will work fine on the reference interpreter. It's possible that this is portable (there is no note claiming otherwise), but I can't be sure:

inspect.stack()[0].lineno

Upvotes: 3

Related Questions