简体   繁体   English

查看从 function 中调用的所有函数的代码

[英]View the code of all the functions being called from within a function

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:要查看beta function 的源代码,我们可以这样做:

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 ?如果我只知道我的 function 被命名为beta ,我如何查看betaalpha和所有从beta调用的函数的源代码?

So... go back to your initial post and put the functions into the interpreter directly.所以... go 回到您的初始帖子并将函数直接放入解释器。 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.这将为您提供可由 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).显示的加载程序function 不是用户定义的,因此您可以忽略它(就此而言,可能任何以双下划线开头和结尾的内容)。

Save the two modules into a.py file (let's pick test.py as an example).将这两个模块保存到一个 .py 文件中(我们以 test.py 为例)。 Now open an interactive python session and:现在打开一个交互式 python session 和:

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.如果您启动 python,它将不起作用,然后输入函数,因为检查需要具有函数来源的源代码。 The items available without the source are already compiled into bytecode, so wouldn't provide you with anything readable.没有源代码的可用项目已经编译成字节码,因此不会为您提供任何可读的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM