UserDict and items()
Remco Gerlich
scarblac at pino.selwerd.nl
Thu Mar 8 02:32:22 EST 2001
Oliver Hofmann <a2619725 at smail.uni-koeln.de> wrote in comp.lang.python:
> Is there a more elegant way to handle items(), values() etc than
> overwriting each function?
>
> One way would be to set data[key] to the required value during
> init(); however I'd like to postpone fetching data from the database
> until the time it is actually requested.
>
> Any help would be appreciated,
It's early morning, but it seems to me that when items() is called, that is
when all the entries are actually requested, so that is the latest point at
which you can set all the data[key] things from the database values. Use
some sort of flag so that you only do this the first time items() is called?
(this won't work well when the database values change, but it seems they
don't since you considered the possibility of doing it in __init__).
Or maybe the intended behavior is to let items() returns only those values
that have been asked for already. You could make __getitem__ put the values
into the dict whenever something special is asked for, ie
def __getitem__(self, key):
if key == "special" and not self.data.has_key(key):
self.data[key] = DatabaseCall(key)
return self.data[key]
Of course to make that 'if' work you shouldn't initialize that value (why do
that anyway, you handle it with getitem).
The cuteness introduced in later Python versions would allow that to be:
def __getitem__(self, key):
return self.data.setdefault(key, DatabaseCall(key))
Ie, look up everything in the database that's not in the dictionary yet, put
it in, and return what's in the dict.
The last option is not to use items() :-)
--
Remco Gerlich
More information about the Python-list
mailing list