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

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

Looked at the inspection

inspect.getsourcelines(object)    

which also gives the line number as a result.

I see that for methods with decorators the line is No.. returned from above, checks the functions for the actual source code of the decorator, and not for the desired source code of the function. So, any way to trick this? (I understand that the interpreter is doing something like a wrapper function inside the decorator at runtime, but I could be wrong)

+5
source share
2 answers

In general, there is no easy solution.

- , , , "" , , .

, , -, "" , . code ( .func_code), , .

>>> 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
>>> 
+4

wrapt , , , . functools.wraps.

+1
source

All Articles