python - Dict-like object with no __getitem__, __setitem__ -


if

import gdbm db = gdbm.open('foo', 'cs') 

you object is:

<gdbm.gdbm @ 0x7f0982b9aef0> 

you can set keys , values in database via:

db['foo'] = 'bar' print db['foo'] 

i wanted use these twisted , make wrapper __getitem__ , __setitem__ returns deferreds. however, noticed peculiar:

in [42]: dir(db) out[42]: ['close', 'firstkey', 'has_key', 'keys', 'nextkey', 'reorganize', 'sync'] 

this object hasn't got __getitem__ , __setitem__. trying either of these gives attribute access error. yet, behaves dictionary. sort of object this?

(i suspect c extension object, find odd has dict-like access methods, no __getitem__ , __setitem__ methods. pointer python doc describing behavior helpful.)

further: how references db.__getitem__ , db.__setitem__ if wanted wrap them in deferred? solution see wrap db in utility class:

class db:     def __init__(self, db):          self.db = db      def __getitem__(self, x):          return self.db[x]      ... 

but perhaps missing obvious?

gdbm indeed c module; object implements c-api mapping protocol instead.

see source code pymappingmethods structure function pointers.

you use operator.getitem() access keys:

>>> operator import getitem >>> db['foo'] = 'bar' >>> getitem(db, 'foo') 'bar' 

you wrap getitem() in functools.partial() make efficient callable 1 argument:

>>> functools import partial >>> gi = partial(getitem, db) >>> gi('foo') 'bar' 

as getitem , partial implemented in c, combo faster custom objects, functions or lambdas wrap access.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -