Hello,

googling I found several ways of implementing a "dictionary with attribute-style access".

1. ActiveState cookbook: http://code.activestate.com/recipes/473786/

2. ActiveState cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668

3. web2py codebase: Storage(dict)

I enclosed the three implementations below.

My question to the Python specialists: which one is the most correct?
Are there restrictions with regards to pickling or copy()?
Which one should I choose?

Regards, Andreas

--
Andreas Balogh
baloand (at) gmail.com

-----------------------------------------------------------------------
class AttrDict(dict):
    """ comments removed """
"""A dictionary with attribute-style access. It maps attribute access to the real dictionary. """
        def __init__(self, init={}):
                dict.__init__(self, init)

        def __getstate__(self):
                return self.__dict__.items()

        def __setstate__(self, items):
                for key, val in items:
                        self.__dict__[key] = val

        def __repr__(self):
                return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))

        def __setitem__(self, key, value):
                return super(AttrDict, self).__setitem__(key, value)

        def __getitem__(self, name):
                return super(AttrDict, self).__getitem__(name)

        def __delitem__(self, name):
                return super(AttrDict, self).__delitem__(name)

        __getattr__ = __getitem__
        __setattr__ = __setitem__

        def copy(self):
                ch = AttrDict(self)
                return ch
-----------------------------------------------------------------------
class attrdict(dict):
    """ comments removed """
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.__dict__ = self
-----------------------------------------------------------------------
class Storage(dict):
    """ comments removed """
    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError, k:
            return None

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

    def __delattr__(self, key):
        try:
            del self[key]
        except KeyError, k:
            raise AttributeError, k

    def __repr__(self):
        return '<Storage ' + dict.__repr__(self) + '>'

    def __getstate__(self):
        return dict(self)

    def __setstate__(self, value):
        for (k, v) in value.items():
            self[k] = v
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to