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)
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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With