UserDict and setattr

Chad Everett chat at
Tue Jun 26 19:56:55 CEST 2001

Using UserDict and overriding getattr, I can create dictionary wrappers
that allow dictionary lookups via getattr.  Using the example below:

apple = Fruit( {'name':"apple",'color':'red'} )
carrot = Veggie( {'name':"carrot",'color':'orange'} )

apple.color         # returns 'red'
apple['color']      # returns 'red'

apple['color'] = 'green'
apple.color         # returns 'green'
apple['color']      # returns 'green'

apple.color = 'brown'
apple.color         # returns 'brown'
apple['color']      # returns 'green"  !!!!!!!!!

Obviously, setattr needs to be altered to also update
the dictionary (via __setitem__) and not just the instance's 

I cannot seem to find a way to override setattr so that I 
can get the get a __setitem__ called to update the dictionary.

Please Help!!!

Code sample follows:

import UserDict

class DictWrap(UserDict.UserDict):

    def __init__(self,initdict): = initdict
    def __getattr__(self,name):

class Fruit(DictWrap):

    def __init__(self,initdict):

class Veggie(DictWrap):

    def __init__(self,initdict):

apple = Fruit({'name':"apple",'color':'red'})
carrot = Veggie({'name':"carrot",'color':'orange'})

-----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----

More information about the Python-list mailing list