有什么方法可以在运行时影响本地人吗? [英] Is there any way to affect locals at runtime?

查看:89
本文介绍了有什么方法可以在运行时影响本地人吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上想创建一个新的本地.我知道这听起来很可疑,但是我认为我有一个很好的用例.本质上我的问题是,当我尝试打印鸡蛋时,此代码将引发"NameError:全局名称'eggs'未定义":

I actually want to create a new local. I know it sounds dubious, but I think I have a nice use case for this. Essentially my problem is that this code throws "NameError: global name 'eggs' is not defined" when I try to print eggs:

def f():
    import inspect
    frame_who_called = inspect.stack()[1][0]
    frame_who_called.f_locals['eggs'] = 123

def g():
    f()
    print(eggs)

g()

我发现了这个老东西: http://mail.python.org/pipermail/python- dev/2005-January/051018.html

I found this old thing: http://mail.python.org/pipermail/python-dev/2005-January/051018.html

这意味着我也许可以使用ctypes并调用一些秘密函数来做到这一点,尽管他们只是在谈论更新值.但是也许有一种更简单的方法?

Which would mean I might be able to do it using ctypes and calling some secret function, though they only talked about updating a value. But maybe there's an easier way?

推荐答案

正如Greg Hewgill在对该问题的评论中提到的那样,我回答了

As Greg Hewgill mentioned in a comment on the question, I answered another question about modifying locals in Python 3, and I'll give a bit of a recap here.

关于此问题的帖子在Python 3错误列表中 –文献记载不多在Python 3手册中. Python 3使用本地数组而不是Python 2中的字典-优点是本地变量的查找时间更快(Lua也这样做).基本上,该数组是在字节码编译时"定义的,无法在运行时进行修改.

There is a post on the Python 3 bug list about this issue -- it's somewhat poorly documented in the Python 3 manuals. Python 3 uses an array for locals instead of a dictionary like in Python 2 -- the advantage is a faster lookup time for local variables (Lua does this too). Basically, the array is defined at "bytecode-compile-time" and cannot be modified at runtime.

具体参见错误列表上的乔治·布兰德尔(Georg Brandl)的最后一段,详细了解为什么无法(可能永远不会)在Python 3中工作.

See specifically the last paragraph in Georg Brandl's post on the bug list for finer details about why this cannot (and probably never will) work in Python 3.

这篇关于有什么方法可以在运行时影响本地人吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆