gpt4 book ai didi

python - 如何获取Python中动态定义函数的源代码?

转载 作者:行者123 更新时间:2023-12-02 00:52:04 24 4
gpt4 key购买 nike

在 Python 中动态定义代码时(例如,通过 exec 或从 import 以外的其他媒介加载代码),我无法获取已定义代码的源代码功能。

inspect.getsource 似乎从加载的位置查找已加载的模块。

import inspect

code = """
def my_function():
print("Hello dears")
"""
exec(code)
my_function() #Works, as expected
print(inspect.getsource(my_function)) ## Fails with OSError('could not get source code')

是否有其他方法可以获取动态解释函数(或其他对象)的源代码?

最佳答案

Is there any other way to get at the source of a dynamically interpreted function (or other object, for that matter)?

一种选择是将源代码转储到文件中并从那里执行,尽管这会在文件系统中留下需要清理的垃圾。

一个不太可靠但垃圾较少的替代方案是使用 astor.to_source() 从字节码重建源代码(-ish)例如。它将为您提供“相应的”源,但与原始源相比可能会改变格式或丢失元数据。

最简单的方法是将原始源附加到创建的函数对象:

code = """
def my_function():
print("Hello dears")
"""
exec(code)
my_function.__source__ = code # has nothing to do with getsource

另一种选择(虽然在这里可能没用,因为我假设您希望从模板动态创建主体)是将代码对象交换为您使用正确/相关的firSTLineno更新的代码对象(并且可以选择文件名(尽管您可以将其设置为编译语句的一部分)。仅当出于某种奇怪的原因,您将 Python 代码直接嵌入到其他文件中,但不能或不想将其提取到自己的模块中进行正常评估时,这才有用。

关于python - 如何获取Python中动态定义函数的源代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59244323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com