在Python3中使用contextmanager(我还没有测试Python2)对于在with
子句范围内声明的变量有一些奇怪的行为
在我看来,这些变量的行为就像是“远处的幽灵行动”,因为只有在观察到它们时,它们才似乎存在(一个不懂物理的工程师开的玩笑)
如果你
locals()
那么变量不存在
但如果你:
locals()
李>那么变量存在强>
请参见此示例:
from contextlib import contextmanager
def groucho():
@contextmanager
def groucho_manager(**kwargs):
yield
print("groucho_manager locals", locals())
a
with groucho_manager(lolcat=10):
a = 50
def harpo():
@contextmanager
def harpo_manager(**kwargs):
yield
print("harpo_manager locals", locals())
with harpo_manager(lolcat=10):
b = 100
groucho()
harpo()
产出:
groucho_manager locals {'kwargs': {'lolcat': 10}, 'a': 50}
harpo_manager locals {'kwargs': {'lolcat': 10}}
可能与Python class inheritance - spooky action有关,但我不确定
我最初的用例是制作一个
inner scope aware context manager
来处理日志记录我认为我可以滥用问题中列出的奇怪行为,但正如@jasonharper所指出的:这与嵌套作用域有关,不能滥用
所以。。。我决定为所有这些问题制定一个真正骇客/滥用的解决方案:
关于pypi的scope_injected_contextmanager
以下是自述文件中的简单示例:
详见github
小心。。。its:
相关问题 更多 >
编程相关推荐