dictionary and __getattr__

Heiko Wundram heikowu at ceosg.de
Thu Sep 6 07:07:47 EDT 2001


On Thursday 06 September 2001 11:54, you wrote:
> Wouldn't it be nice if this would work:
>
>   d = {'x': 1}
>   print d.x
>
> i.e. every entry in a dictionary is also an attribute of the
> dictionary itself.
>
> Is there a class wrapper for that somewhere available?

# Works with Python 2.2a2.

from __future__ import generators

class AttributeDictionary:

    def __init__(self):
        self.dict = {}
        self.default = None

    def __getitem__(self, key):
        return self.dict[key]

    def __setitem__(self, key, value):
        self.dict[key] = value

    def __delitem__(self, key):
        del self.dict[key]

    def __getattr__(self, key):
        if not key in self.dict:
            raise AttributeError
        return self.dict[key]

    def __setattr__(self, key, value):
        self.dict[key] = value

    def __delattr__(self, key):
        del self.dict[key]

    def get(self, key, default=None):
        try:
            return self[key]
        except:
            if default == None:
                return self.default
            else:
                return default

    def setdefault(self, default):
        self.default = default

    def has_key(self, key):
        try:
            self[key]
            return 1
        except:
            return 0

    def __iter__(self):
        for i in self.dict:
            yield i
        raise StopIteration

>
>   Harald Kirsch

Works (almost like a dictionary). I've left out the more exotic dictionary 
functions like update, etc, for demonstration purposes only. The rest works 
as is.

-- 
Yours sincerely,

	Heiko Wundram




More information about the Python-list mailing list