Reputation: 1261
Take the following functions:
def alpha(a):
return a**2
def beta(a):
return alpha(a)+1
To view the source code of the beta
function we can do:
import inspect
inspect.getsource(beta)
Question:
How do I view the source code of beta
, alpha
and all the functions which are being called from beta
if I know only that my function is named beta
?
Upvotes: 0
Views: 69
Reputation: 251
So... go back to your initial post and put the functions into the interpreter directly. Then:
for a in beta.__globals__:
if callable(beta.__globals__[a]):
print(a)
Note that there is a double underscore both before and after globals. This will give you a list of functions callable by beta. The loader function that shows up is not user defined, so you can ignore that (probably anything that starts and ends with double-underscore, for that matter).
Upvotes: 1
Reputation: 251
Save the two modules into a .py file (let's pick test.py as an example). Now open an interactive python session and:
python3
Python 3.6.9 (default, Sep 11 2019, 16:40:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> import inspect
>>> print (inspect.getsource(test.beta))
def beta(a):
return alpha(a)+1
>>> print (inspect.getsource(test.alpha))
def alpha(a):
return a**2
It won't work if you start python, then type in the functions as inspect needs to have the source code from whence the functions came. The items available without the source are already compiled into bytecode, so wouldn't provide you with anything readable.
Upvotes: 0