Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get line number of function (with/without a decorator) in a python module?

Tags:

python

I want to get the line number of a python function in the source code. What i have in runtime is module, class, method objects

Had a look at inspect

inspect.getsourcelines(object)    

which also gives line number in result.

I see that for methods with decorators, line no. returned from above inspect function points to the actual decorator's source code rather than desired function's source code. So any way to workaround this? (i understand that interpreter does something like wrapping function inside decorator in runtime, but i might be wrong)

like image 526
Hari Avatar asked Dec 01 '11 09:12

Hari


1 Answers

There is no easy solution in the general case.

A decorator is a function that given a function returns a function, normally by "wrapping" it in a closure that performs the operation for which the decorator has been designed.

The file and line number information are not however in the function object itself and you cannot "fix" them by copying this information from the wrapped function to the wrapper. That data is instead contained in the code object of the function (available with .func_code), and it is shared among all closures you are going to create.

>>> def bar(x):
...     def foo():
...         return x
...     return foo
... 
>>> f1 = bar(1)
>>> f2 = bar(2)
>>> f1()
1
>>> f2()
2
>>> f1.func_code is f2.func_code
True
>>> 
like image 100
6502 Avatar answered Nov 15 '22 13:11

6502