0

Sincesys._getframe().f_back.f_lineno does not work at all in python 3.9, following could be used from now:

from inspect import currentframe


def testLineNumberFunction() -> int:
    return currentframe().f_back.f_lineno


print(f'line number is {testLineNumberFunction()}')

Result:

line number is 8

Is there a faster way to achieve this ?

Because the library inspect seems to be slow as mentioned here by @AlexGranovsky

Manifest Man
  • 873
  • 10
  • 16
  • 1
    Do you only need the name, and not other information like line number, etc? If so, why not `my_function.__name__`, or just explicitly use the string `'my_function'`? – Brian61354270 Aug 13 '21 at 14:12
  • @Brian right, it was about line number, i did update the question accordently – Manifest Man Aug 13 '21 at 15:50

1 Answers1

1

Directly access f_code, don't do f_back.f_code

This will give you function name as in heading

import sys

def f1():
    return sys._getframe().f_code.co_name

print(f1())
f1
Python 3.9.5 (default, May 27 2021, 19:45:35) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> 
>>> def f1():
...     return sys._getframe().f_code.co_name
... 
>>> print(f1())
f1
>>>
eroot163pi
  • 1,791
  • 1
  • 11
  • 23
  • Wow this is crazy, i have tested in Pycharm with the Python 3.8.8 and Python 3.9, from my IDE, it does not recognize the command at all :| – Manifest Man Aug 13 '21 at 15:30
  • 1
    i updated the question i type the wrong question, it was supposed to be about line number not the name, but i just wanted to know why my IDE does not recognize it at all. Thanks for your answer it did help me, it works allthough the IDE does not recognize it `Cannot find reference '_getframe' in 'sys.pyi | sys.pyi'` – Manifest Man Aug 13 '21 at 15:47