UserDict and items()

Oliver Hofmann a2619725 at
Wed Mar 7 21:33:28 CET 2001

Hello everyone!

Been toying around with UserDict lately and stumbled into a problem.
the relevant code:

from UserDict import UserDict

class ClText(UserDict):
    def __init__(self):

        # Set initial value['test'] = ''

    def __getitem__(self, key):
        if key == 'test':
            return 'found'

        return UserDict.__getitem__(self, key)

In short, whenever a few reserved keys are queried I'd like to return
default values or fetch needed values from a database. This works
quite nicely:

>>> a = class.ClText()

>>> a['test']


>>> a.items()
[('test', '')]

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,


Oliver Hofmann  -  University of Cologne  -  Department of Biochemistry
   o.hofmann at - setar at - connla at

   You can present the material, but you can't make me care.
  -- Calvin

More information about the Python-list mailing list