Python dumbdbm,数据什么时候回写到磁盘?

Python dumbdbm, when will data be written back to disk?

我正在使用 Python2.7 的 dumbdbm,但这个问题也适用于 Python3 的 dbm.dumb.

文档说:

dumbdbm.sync()
Synchronize the on-disk directory and data files. This method is called by the sync() method of Shelve objects.

我有三个问题:

  1. 如果我不调用 sync,磁盘文件会更新吗?
  2. 这个函数是否总是将数据写回磁盘,而不是相反?
  3. 如果我打电话给 close 会怎样?

回答此类未在文档中具体说明的问题的一种方法(如果不是唯一的话,也许是最好的方法)是阅读源代码(如果可用,就在这里)。

dumbdbm.py 文件应该在您的 /Python/Lib 目录中,也可以通过 Mercurial 源代码修订控制系统在浏览器中在线查看:

https://hg.python.org/cpython/file/2.7/Lib/dumbdbm.py

首先要注意的是私有 _Database class 开头的较长注释 — 这才是真正的 dumbdbm 数据库 — 因为它似乎通常处理您问题的总体主题似乎是:

class _Database(UserDict.DictMixin):

    # The on-disk directory and data files can remain in mutually
    # inconsistent states for an arbitrarily long time (see comments
    # at the end of __setitem__).  This is only repaired when _commit()
    # gets called.  One place _commit() gets called is from __del__(),
    # and if that occurs at program shutdown time, module globals may
    # already have gotten rebound to None.  Since it's crucial that
    # _commit() finish successfully, we can't ignore shutdown races
    # here, and _commit() must not reference any globals.

可以通过阅读它们的源代码找到有关特定方法的深入信息。鉴于此,以下是我认为 Python:

的 2.7 版问题的答案
  1. 如果我不调用sync,磁盘文件会更新吗?

    从前面的评论来看,只要您的程序正常关闭,它似乎就可以了。

    除此之外,它取决于已调用的方法。有些可能,但只是部分。例如,它看起来像 __setitem__(),这取决于该项目是用于全新密钥还是现有密钥。对于后一种情况,在处理它们的部分末尾有一条评论说(意识到 _commit() 只是 sync() 的另一个名称):

    Note that _index may be out of synch with the directory file now: _setval() and _addval() don't update the directory file. This also means that the on-disk directory and data files are in a mutually inconsistent state, and they'll remain that way until _commit() is called. Note that this is a disaster (for the database) if the program crashes (so that _commit() never gets called).

  2. 而且这个函数是否总是将数据写回磁盘,而不是相反?

    sync() / _commit() 似乎没有将任何数据从磁盘加载回内存。

  3. 如果我调用close怎么办?

    close() 只是调用 _commit(),然后将所有内部数据结构设置为 None,从而阻止任何进一步的数据库操作。

总而言之,如果您想对这里的元主题进行一些幽默的解读,我建议您阅读 Learn to Read the Source, Luke