I found this solution the shortest, which seems to be not implementation specific:
import inspect
def __LINE__(): return inspect.stack()[1].lineno
For some reason I like to use stack
as it returns a list. If I need to go deeper then I use stack()[<n>].frame
.
UPDATE
I have checked the performance! sys._getframe(1).f_lineno
or inspect.currentframe().f_back
is much faster! Instead of calling my __LINE__()
I put directly the _getframe(1)
solution. If called 1e6 times, the gain is over 10 minutes!
UPDATE2
I think I have found an even faster way. If performance does count and the __LINE__
is used inside a single module, then this can be used:
import inspect
__LINE__ = inspect.currentframe()
print(__LINE__.f_lineno)
print(__LINE__.f_lineno)
It prints (a little bit unexpectedly):
3
4