是否要使用上下文管理器?

问题描述 投票:0回答:1

我正在使用Python从头开始设计关系数据库,并且在DB上的操作涉及很多文件操作。我目前正在做的是在初始化过程中以r +模式打开文件,并在关机过程中关闭文件,例如so-

class Table:
    def __init__(self,loc):
        self.file=open(loc,"r+")
    def insert(self,key,value):
        self.file.write((key,value))
        self.file.flush()
        os.fsync()
    def __close__(self):
        self.file.close()

替代方法是在每次调用时使用上下文管理器打开文件,但是我想这会降低效率。给定上下文,首选的处理方式是什么?

python database contextmanager
1个回答
0
投票

instance使用with块,然后用户可以在打开基础文件的同时进行多个调用,同时仍然确保正确的清理。您可以通过使类成为上下文管理器来实现。为方便起见,您可能还想提供一个显式的close方法;遵循约定并将其命名为close,而不是__close__(因为该名称没有任何特殊的dunder方法)。

类似:

class Table:
    def __init__(self, loc):
        self.file = open(loc, "r+")
    def insert(self, key, value):
        self.file.write((key, value))
        self.file.flush()
        os.fsync()
    def close(self):
        self.file.close()
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

现在您可以执行以下操作:

with Table('foo/bar/baz.db') as t:
    for i, j in my_data:
        t.insert(i, j)
© www.soinside.com 2019 - 2024. All rights reserved.