编写一个只能用作上下文管理器的Python类

kuz*_*roo 7 python contextmanager

有没有办法在Python中编写一个会出错的类,除非它与with语句一起使用?

# Okay:
with Foo() as f1:
    f1.func1()
    f1.func2()

# Not okay:
f2 = Foo()
f2.func1()
Run Code Online (Sandbox Code Playgroud)

我可以手动完成:__enter__设置一个标志并让其他方法检查该标志.但有更好的方法吗?

以下是不那么自然的代码:

class Foo(object):
    def __init__(self):
        self._entered = False

    def __enter__(self):
        self._entered = True
        return self

    def _verify_entered(self):
        if not self._entered:
            raise Exception("Didn't get call to __enter__")

    def __exit__(self, typ, val, traceback):
        self._verify_entered()
        print("In __exit__")

    def func1(self):
        self._verify_entered()
        # do stuff ...

    def func2(self):
        self._verify_entered()
        # do other stuff
Run Code Online (Sandbox Code Playgroud)

Ami*_*ory 5

从技术上讲,我认为 agf 是正确的,你可以使用元类来自动化这些东西。但是,如果我正确理解了其背后的基本动机,我会建议采用不同的方式。

假设您有一个Payload要通过上下文管理器保护的类。在这种情况下,您只需创建一个返回它的上下文管理器:

# This should go in a private module.
class Payload(object):
    def __init__(self):
        print 'payload ctor'

# This should go in the public interface.
class Context(object):
    def __init__(self):
        # Set up here the parameters.
        pass

    def __enter__(self):
        # Build & return a Payload object
        return Payload()

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Cleanup
        pass

with Context() as f:
    # f here is a Payload object.
Run Code Online (Sandbox Code Playgroud)

如果你躲在Payload一个私人模块中,那就很好了。