Abhi
Abhi

Reputation: 1147

Database-backed dictionary with arbitrary keys

The python shelf module 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!

Upvotes: 0

Views: 286

Answers (4)

NorthGuard
NorthGuard

Reputation: 11

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

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881595

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.

Upvotes: 1

tamasd
tamasd

Reputation: 5913

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

Upvotes: 0

Noah
Noah

Reputation: 22646

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

Upvotes: 1

Related Questions