我正在研究一个实现上下文管理器的类似连接的对象。强烈鼓励写这样的东西:

with MyConnection() as con:
    # do stuff

当然也可以做到这一点:
con = MyConnection()
# do stuff
con.close()

但未能关闭连接是相当有问题的。所以关闭 __del__() 似乎是个好主意:
def __del__(self):
    self.close()

这看起来很不错,但有时会导致错误:
Exception ignored in: [...]
Traceback (most recent call last):
  File "...", line xxx, in __del__()
TypeError: 'NoneType' object is not callable

当调用 __del__() 时,似乎有时 close 方法已经被销毁。

所以我正在寻找一种很好的方法来鼓励 python 在破坏时正确关闭连接。如果可能,我想避免 close()__del__() 中的代码重复

最佳答案

如果你真的想阻止用户不关闭连接,你可以只在 __enter__ 中初始化它,或者你可以添加一个标志来发现它没有被上下文管理器初始化。例如,像

class MyConnection(object):

    safely_initialized = False

    def __enter__(self):
        # Init your connection
        self.safely_initialized = True
        return self

    def do_something(self):
        if not self.safely_initialized:
            raise Exception('You must initialize the connection with a context manager!')
        # Do something

    def __exit__(self, type, value, traceback):
        # Close your connection

这样,除非在上下文管理器中,否则不会初始化连接。

10-07 13:11