Playing with Dict - Can anyone see a way around this?

Alex Martelli aleaxit at yahoo.com
Sat May 19 03:43:52 EDT 2001


<s713221 at student.gu.edu.au> wrote in message
news:3B069A99.18AF2522 at student.gu.edu.au...
    ...
> def __getattr__(self,key):
>     if key in ['keys','items','values']:
>         return self.__dict__[key]

Note that this part is unnecessary: __getattr__ is never called
for an attribute name that is found in the obj's __dict__ (it's
different for __setattr__).

>         class __keys:
>                 def __init__(self,dict):
>                         self.dict = dict
>                 def __repr__(self):
>                         return str(self.dict.keys())
>                 def __call__(self):
>                         return self.dict.keys()
>                 def __getitem__(self,item):
>                         return self.dict.keys()[item]

Simpler and maybe faster:
            class __keys:
                def __init__(self, dict):
                    self.keys = dict.keys()
                def __repr__(self):
                    return repr(self.keys)
                def __call__(self):
                    return self.keys
                def __getitem__(self, item):
                    return self.keys[item]

Calling self.dict.keys() repeatedly for each use should be slower
than calling it once and caching the result.  Besides:

> Whoops. Not what I wanted. And this invalidates my aim of having a.keys
> and a.keys() acting the same way.
> >>> for i in a.keys():
> print i
> del a[i]

now 'for i in a.keys' will also let you alter a during the loop.

An optional little enhancement is to add a second line to the
__keys' __init__:
                    self.keys.sort()
The sort shouldn't slow things down by much, and often it's
nicer to see the keys in sorted order:-).

This however would not keep the property of corresponding
order between keys, items and values (when called without
intervening alterations to the dictionary).  But that is not
used very often anyway.


Alex






More information about the Python-list mailing list