UserDict and items()

Oliver Hofmann a2619725 at smail.uni-koeln.de
Wed Mar 7 15:33:28 EST 2001


Hello everyone!


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

---
from UserDict import UserDict

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

        # Set initial value
        self.data['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']
'found'

Unfortunately:

>>> 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


--
Oliver Hofmann  -  University of Cologne  -  Department of Biochemistry
   o.hofmann at smail.uni-koeln.de - setar at gmx.de - connla at thewell.com

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






More information about the Python-list mailing list