开发者

Database-backed dictionary with arbitrary keys

开发者 https://www.devze.com 2022-12-30 09:20 出处:网络
The python shelf modu开发者_Go百科le only seems to be allow string keys. Is there a way to use arbitrary typed (e.g. numeric) keys? May be an sqlite-backed dictionary?

The python shelf modu开发者_Go百科le only seems to be allow string keys. Is there a way to use arbitrary typed (e.g. numeric) keys? May be an sqlite-backed dictionary?

Thanks!


Why not convert your keys to strings? Numeric keys should be pretty easy to do this with.


You can serialize on the fly (via pickle or cPickle, like shelve.py does) every key, as well as every value. It's not really worth subclassing shelve.Shelf since you'd have to subclass almost every method -- for once, I'd instead recommend copying shelve.py into your own module and editing it to suit. That's basically like coding your new module from scratch but you get a working example to show you the structure and guidelines;-).

sqlite has no real advantage in a sufficiently general case (where the keys could be e.g. arbitrary tuples, of different arity and types for every entry) -- you're going to have to serialize the keys anyway to make them homogeneous. Still, nothing stops you from using sqlite, e.g. to keep several "generalized shelves" into a single file (different tables of the same sqlite DB) -- if you care about performance you should measure it each way, though.


I think you want to overload the [] operator. You can do it by defining the __getitem__ method.


I ended up subclassing the DbfilenameShelf from the shelve-module. I made a shelf which automatically converts non-string-keys into string-keys and returns them in original form when queried. It works well for Python's standard immutable objects: int, float, string, tuple, boolean.

It can be found in: https://github.com/North-Guard/simple_shelve

0

精彩评论

暂无评论...
验证码 换一张
取 消