I tried this code-snippet inside a script named test.py
:
from inspect import *
def f1(p,r):
"""Return f1 score from p,r"""
return 2*p*r/(p+r)
print(getsourcelines(f1))
If I run this from terminal with python3 test.py
, it outputs the following :
(['def f1(p,r):\n', '\t"""Return f1 score from p,r"""\n', '\treturn 2*p*r/(p+r)\n'], 3)
But, if I run the same whole script line by line inside python shell, it throws a OSError
. This is what I tried in python shell along with the error :
>>> from inspect import *
>>>
>>> def f1(p,r):
... """Return f1 score from p,r"""
... return 2*p*r/(p+r)
...
>>> print(getsourcelines(f1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/inspect.py", line 955, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python3.6/inspect.py", line 786, in findsource
raise OSError('could not get source code')
OSError: could not get source code
>>>
Why does inspect.getsourcelines(f1)
throws error inside python shell, but not when it is run form the file? Is there any other way to get the source lines of a function declared inside a python shell?