gpt4 book ai didi

Python 2 使用全局关键字和闭包注入(inject)模块范围

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:31 25 4
gpt4 key购买 nike

tl;dr:是否可以将带有 global 关键字的函数注入(inject)到模块中,注入(inject)的方式是 global关闭那个模块? (如何或为什么不?)


带有示例的长版

Runtime injection of attributes into module namespace中建议要注入(inject)模块的命名空间,可以使用 setattr 方法:

import foo

## before
try:
foo.bar()
except AttributeError:
print 'ok'

# expected to print 'ok'

## magic
def bar():
pass

setattr(foo,'bar',bar)

## after
foo.bar()
# expected to do nothing (instead of raising an error)

然而,这似乎无法像人们希望的那样使用 global 关键字。例如:

## foo.py
a = 4
def bar():
global a
a = 5
def check(expectation):
global a
assert a == expectation, "%s == %s"%(a,expectation)
a = 4

## rab.py
import foo
foo.bar()
# expected to return and it does
foo.check(5)
print 'bar: ok'
def rab():
global a
a = 6
setattr(foo,'rab',rab)
foo.rab()
# may be expected to return but it raises AssertionError:
foo.check(6)
print 'rab: ok' # never printed

是否有可能以foo.afoo.check时变成6的方式注入(inject)rab > 运行,同时保持原来的 foo.check?

是否可以将带有 global 关键字的函数注入(inject)模块,注入(inject)的 global 会在该模块上关闭? (如何或为什么不?)

最佳答案

rab 的全局字典已内置。您可以在 rab.func_globals 中看到它。

属性是只读的,所以你不能替换它

您可以在 foo 中创建一个新函数,并将 rab 中的代码推送到其中 :)

type(rab)(rab.func_code, foo.__dict__)

例如。

## rab.py
import foo
foo.bar()
# expected to return and it does
foo.check(5)
print 'bar: ok'
def rab():
global a
a = 6
foo.rab = type(rab)(rab.func_code, foo.__dict__)
foo.rab()
# may be expected to return but it raises AssertionError:
foo.check(6)
print 'rab: ok'

但不要这样做

关于Python 2 使用全局关键字和闭包注入(inject)模块范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23474162/

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