为什么 Python 的搁置要求所有键都是字符串? [英] Why does Python's shelve require that all keys be strings?

查看:67
本文介绍了为什么 Python 的搁置要求所有键都是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 的 shelve 模块要求所有键都是字符串,并且有各种解决方法(参见线程 此处这里).我的问题是,为什么搁置需要字符串键?鉴于我可以腌制一个使用其他对象作为键的字典,并且搁置在引擎盖下使用腌制,为什么搁置本身不能处理这些键?字符串键是否让只更新持久对象的一部分变得更加简单,而不必重写整个对象(如果是,为什么)?

It's well-documented that Python's shelve module requires all keys to be strings and that there are various workarounds (see threads here and here). My question is, why does shelve require string keys? Given that I can pickle a dict that uses other objects as keys, and that shelve uses pickle under the hood, why can't shelve handle such keys itself? Do string keys make it vastly simpler to update only a piece of the persistent object rather than having to rewrite the whole thing (and if so, why)?

推荐答案

因为在底层,shelve 模块使用 bsddb、gdbm 或 dbm 之一进行存储,并且它们仅支持字符串键.

Because under the hood the shelve module uses one of bsddb, gdbm or dbm for storage, and they support only string keys.

您可以pickle 使用其他对象作为键的字典是对的,但是当一个键更改时,您必须刷新整个存储.通过使用像这样的键值数据库,只会刷新更改的值.

You're right that you can pickle a dict that uses other objects as keys, but then when one key changes, you have to flush the whole storage. By using a key-value database like those, only the changed values are flushed.

这篇关于为什么 Python 的搁置要求所有键都是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆