'Python equivalent to C++ __LINE__

A useful print for debugging in C++ is

std::cout << __LINE__ << std::endl;

Of course you can simply print a string with the line number, for example:

std::cout << "this is line 54" << std::endl;

but it won't keep changing the line number when you move it around. Is there any equivalent macro in Python?



Solution 1:[1]

As a function, so you don't have to expand it everywhere

import sys

def LINE():
    return sys._getframe(1).f_lineno


print('This is line', LINE())

TBH I've never understood the point of the inspect module at all.

Solution 2:[2]

No macro, but you can do

from inspect import currentframe, getframeinfo

print(getframeinfo(currentframe()).lineno)

To get the current line number in Python.

The "current line number" will be the line where currentframe() is evaluated, FYI.

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 o11c
Solution 2 CoffeeTableEspresso
Solution 3