访问Python源代码:剖析函数的代码对象
CPython允许访问函数对象的代码对象。
__code__Object包含功能的原始字节码(CO_CODE)以及其他信息,如常量和变量名称。
def fib(n): if n <= 2: return 1 return fib(n-1) + fib(n-2) dir(fib.code) def fib(n): if n <= 2: return 1 return fib(n-1) + fib(n-2) dir(fib.code)
显示python函数的字节码
Python解释器在在Python的虚拟机上执行它之前将代码编译为字节码
以下是如何查看Python函数的字节码
import dis def fib(n): if n <= 2: return 1 return fib(n-1) + fib(n-2) Display the disassembled bytecode of the function. dis.dis(fib)
DIS模块中的dis.dis函数将返回传递给它的函数的分解字节码。
Python 显示对象的源代码
非内置对象
要打印Python对象检查的源代码使用inspect。
请注意,这不适用于内置对象,也不适用于交互方式定义的对象。
以下是如何从随机模块random打印方法RandInt的源代码:
import random import inspect print(inspect.getsource(random.randint)) Output: def randint(self, a, b): """Return random integer in range [a, b], including both end points. """ #return self.randrange(a, b+1)
只需打印文档字符串
print(inspect.getdoc(random.randint)) Output: Return random integer in range [a, b], including both end points.
Python查看方法random.randint在哪个文件中定义:
print(inspect.getfile(random.randint))
输出
c:\Python35\lib\random.py
或者:
print(random.randint.code.co_filename) # equivalent to the above
交互式定义的对象
Python如何查看交互式定义的对象的源代码
如果以交互方式定义对象,则不能提供源代码,但可以改用dill.source.getsource
define a new function in the interactive shell def add(a, b):
return a + b print(add.code.co_filename) # Output: import dill print dill.source.getsource(add) def add(a, b): return a + b
内置对象
Python如何查看内置对象的源代码
Python内置函数的源代码是用C写入的,只能通过查看Python的源代码上访问。
print(inspect.getsource(sorted)) # raises a TypeError type(sorted) #
访问Python源代码和字节码在许多情况下都有用。
日期:2020-06-02 22:16:03 来源:oir作者:oir