如何在 Python 中获取/设置函数的局部变量(从外部)? [英] How to get/set local variables of a function (from outside) in Python?
问题描述
如果我有一个函数(在 Python 2.5.2 中),例如:
If I have a function (in Python 2.5.2) like:
def sample_func():
a = 78
b = range(5)
#c = a + b[2] - x
我的问题是:
- 如何在函数内部使用locals()从外部获取函数的局部变量(a,b)?(一种反思)
- 是否可以从外部设置局部变量(比如 x),以便注释行起作用?(我知道这听起来很奇怪).
提前致谢.
编辑:
每个人都在要求一个用例.但这是一个奇怪的情况.(不要怪我,我没有创造它).这是场景:
Everyone is asking for a use-case. But it is a weird situation. (Don't blame me, I did not create it). Here is the scenario:
- 我有一个包含 python 函数的加密 python 源文件.
- C 扩展模块对其进行解密并在内存中构建该函数.
- 一个主要的 python 程序首先调用带有加密文件位置的 C 扩展.
- 然后主程序调用已在内存中构建的函数(通过 C 扩展)
- 但是主程序需要知道那个函数的局部变量(别问我为什么,不是我)
- 出于某种(该死的)原因,主程序也需要设置一个变量(最奇怪的)
推荐答案
没有.没有运行的函数没有局部变量;这只是一个函数.在函数未运行时询问如何修改函数的局部变量就像在程序未运行时询问如何修改程序的堆一样.
No. A function that isn't being run doesn't have locals; it's just a function. Asking how to modify a function's locals when it's not running is like asking how to modify a program's heap when it's not running.
不过,如果您真的愿意,您可以修改常量.
You can modify constants, though, if you really want to.
def func():
a = 10
print a
co = func.func_code
modified_consts = list(co.co_consts)
for idx, val in enumerate(modified_consts):
if modified_consts[idx] == 10: modified_consts[idx] = 15
modified_consts = tuple(modified_consts)
import types
modified_code = types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, modified_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab)
modified_func = types.FunctionType(modified_code, func.func_globals)
# 15:
modified_func()
这是一个黑客,因为没有办法知道 co.co_consts 中的哪个常量是哪个;这使用一个哨兵值来解决它.取决于您是否可以充分限制您的用例,这可能就足够了.
It's a hack, because there's no way to know which constant in co.co_consts is which; this uses a sentinel value to figure it out. Depending on whether you can constrain your use cases enough, that might be enough.
这篇关于如何在 Python 中获取/设置函数的局部变量(从外部)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!