Python equivalent to C++ __LINE__

Viewed 2931

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?

4 Answers

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.

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.

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

Define a class with the __str__ method returns the current line number:

import inspect

class LineNo:
    def __str__(self):
        return str(inspect.currentframe().f_back.f_lineno)


__line__ = LineNo()

Now it's more similar to C++:

print(__file__, __line__)
Related