将变量注入调用者的作用域? [英] Injecting variables into the caller's scope?

查看:30
本文介绍了将变量注入调用者的作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以定义一个函数,在调用时将新的局部变量插入调用者的作用域吗?我有一种感觉,将调用者的 locals() 传递给函数可能会起作用,但是有没有一种方法可以做我想做的事而不必这样做?

Can I define a function which, when called, inserts new locals into the caller's scope? I have a feeling that passing the caller's locals() into the function might work, but is there a way to do what I want without having to do this?

推荐答案

根据 Python 的规则,你不能改变调用者的locals;在当前的实现中,如果您尝试(例如使用 Anurag 建议的黑魔法),您将不会收到异常(尽管我想将该错误检查添加到某个未来版本中),但是如果您的调用者是一个函数(如果你的调用者是模块顶级代码,则不是)——调用者的实际局部变量实际上不会受到影响.这适用于调用者的 locals 是显式传入还是通过黑魔法获取:如果您的代码要保持理智,它们仍然需要被视为只读 dict.

By Python's rules, you cannot alter your caller's locals; in the current implementations, if you try (e.g. with the black magic Anurag suggests) you will not get an exception (though I'd like to add that error check to some future version), but it will be essentially inoperative if your caller is a function (not if your caller is module top-level code) -- the caller's actual local variables won't in fact be affected. This holds whether the caller's locals are explicitly passed in, or fetched through black magic: they still need to be treated as a read-only dict if your code is to have any sanity.

相反,您可以让调用者传入一个明确的、真实的、普通的 dict(如果需要,可以从 locals() 初始化),并且您的代码在该 dict 中所做的所有更改都将仍然供调用者使用——当然只是不是调用者本地范围内的新裸名",但无论调用者需要使用 x['foo']x.foo 或(如您所愿)只是裸名 foo.

Rather, you could have the caller pass in an explicit, real, normal dict (which could be initialized from locals() if you want), and all alterations your code does in that dict will still be there for the caller's use -- just not as "new barenames" in the caller's local scope of course, but the functionality is the same whether the caller needs to use x['foo'] or x.foo or (as you'd prefer) just barename foo.

顺便说一句,要使用属性访问语法而不是字典索引语法,您可以:

BTW, to use attribute-access syntax rather than dict indexing syntax, you can do:

class Bunch(object): pass

...

# caller code
b = Bunch()
thefun(b)
print b.foo

...

# called function
def thefun(b):
  b.foo = 23

这也涵盖了thefun 想要使用字典索引语法的情况(假设它的主体是 b['foo'] = 23 而不是 b.foo = 23):在这种情况下,调用者只需要使用 thefun(vars(b)) 而不是普通的 thefun(b),但之后它可以继续使用 b.foo 访问语法.

This also covers, with a tiny variation, the case in which thefun wants to work with dict indexing syntax (say its body is b['foo'] = 23 instead of b.foo = 23): in that case, the caller just needs to use thefun(vars(b)) instead of the plain thefun(b), but it can keep working with the b.foo access syntax afterwards.

这篇关于将变量注入调用者的作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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