Python@contextmanager方法模仿开放文件方法?

Python@contextmanager方法模仿开放文件方法?,python,contextmanager,Python,Contextmanager,我目前正在处理一个会话类,该类应该正常启动或使用with语句启动。我还需要为每个会话共享一些伪全局值: session1 = Session(a, b ,c) session2 = Session(x, y, z) session1.start() # Using session1 with a global value here with session2.start(): # Using session2 with global value copy # Coming back

我目前正在处理一个
会话
类,该类应该正常启动或使用
with
语句启动。我还需要为每个会话共享一些伪全局值:

session1 = Session(a, b ,c)
session2 = Session(x, y, z)
session1.start()
# Using session1 with a global value here

with session2.start():
    # Using session2 with global value copy

# Coming back in session1 with the initial global value
为了管理全局值,我最终使用了
上下文库。(). 

为了将
start()
作为
@contextmanager
进行管理,我尝试处理Python堆栈。但我知道,根据Python版本和解释器的不同,这可能会很棘手

我想执行与
open()
相同的操作,您可以使用两种方法:

f = open('...')
with open('...') as f:
    # Read the file here.
可能吗?你应该怎么做


谢谢你的想法

我认为使用
@contextmanager
是不可能的,但您可以直接将
会话
设置为a类上下文管理器,如下所示:

class Session:
    # ...
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()
    #...

详情如下。文件就是这样做的。对于第三方课程,可能也很方便。

您如何访问这些全局值?此外,使用
open
的示例将导致with语句覆盖f的原始值并将其忘记。这是with语句是关闭的第二个文件,而不是打开的第一个文件之后的f值。使用
@contextmanager
似乎不可能,但您可以在会话类上实现
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。