UserDict and items()

Steve Holden sholden at holdenweb.com
Wed Mar 7 18:51:44 EST 2001


"Oliver Hofmann" <a2619725 at smail.uni-koeln.de> wrote in message
news:98656v$cud$1 at news.rrz.Uni-Koeln.DE...
> 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'] = ''
>
Since __getitem__() is checking for this value, why bother to add it to the
dictionary? Just so items() includes the key? As you see later, when you use
__getitem__() to fake a value for a given key it doesn't appear in items(),
which is just delegated to the underlying dictionary.

>
>     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()
>
wouldn't

a = ClText() be better? "class" is a reserved word.

> >>> a['test']
> 'found'
>
So you can see that your __getitem__() call is working.

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

Such laziness is fine, but it does imply that calls to items(), values() are
going to have to trigger the lazy fetch, and therefore cannot simply be
inherited, I suspect.

>
> Any help would be appreciated,
>
>
I have an idea that a further description of the surrounding application
might allow refactoring of your code to give rthe interface you want.

regards
 Steve





More information about the Python-list mailing list