【发布时间】:2020-03-22 17:53:26
【问题描述】:
我在一个文件中定义了一个python上下文类和一个Test类:
class Test(object):
pass
class MyContext(object):
def __init(self):
self._vars = []
def __enter__(self):
pass
def __exit(self, ....):
pass
在另一个使用该上下文的文件中:
from somewhere import Test, MyContext
with MyContext() as ctx:
mytest = Test()
所以我想要实现的是,当我退出上下文时,我想知道创建的mytest 实例并将其添加到ctx._vars = [<instance of Test >] 中。
我不想拥有ctx.add_var(mytest) 方法,我希望将那些Test 实例自动添加到ctx 实例中。
【问题讨论】:
-
使用上下文并不意味着
ctx知道您的with语句中的代码。 -
正确。一个中间解决方案是将 locals() 传递给 ctx ,最后一行类似。
ctx.get_nodes_from_locals(locals())但我必须过滤 ctx 内部的内容并摆脱可能存在的外部。目前还不是防弹的。 -
在您输入上下文时评估闭包。从内部更改上下文表明您在设计任何东西时都使用了错误的设计工具。
-
(我删除了“python-contextvars”标签,因为这些标签与 with-block 管理的“context”无关
标签: python introspection