Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent to C++ __LINE__

Tags:

python

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?

like image 746
A. Frenzy Avatar asked Jun 25 '19 21:06

A. Frenzy


4 Answers

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.

like image 144
o11c Avatar answered Oct 22 '22 19:10

o11c


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.

like image 28
CoffeeTableEspresso Avatar answered Oct 22 '22 20:10

CoffeeTableEspresso


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
like image 2
TrueY Avatar answered Oct 22 '22 20:10

TrueY


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__)
like image 2
Elyar Adil Avatar answered Oct 22 '22 20:10

Elyar Adil