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

时间:2015-03-04 15:29:20

标签: python contextmanager

我目前正在开发一个Session类,应该正常启动或使用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

为了管理全球价值,我最终使用了Contextual库。 (https://pypi.python.org/pypi/Contextual)。

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

我想和open()做同样的事情,你可以两种方式使用:

f = open('...')
with open('...') as f:
    # Read the file here.

有可能吗?你应该怎么做?

感谢您的想法!

1 个答案:

答案 0 :(得分:2)

我认为@contextmanager不可能,但您可以直接将Session类作为上下文管理器:

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

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

详情为here。这就是文件的完成方式。对于第三方派对,contextlib.closing也可能很方便。