Seite 1 von 1

ImmutableDict()

Verfasst: Montag 14. Juli 2014, 19:50
von jens
Hab http://legacy.python.org/dev/peps/pep-0416/ gefunden und dort wurde auf brownie.datastructures.ImmuatableDict verwiesen: https://github.com/DasIch/brownie/blob/ ... appings.py

Ich hab das draus gemacht:

Code: Alles auswählen

class ImmutableDict(dict):
    """
    Based on borrowed code from:
    https://github.com/DasIch/brownie/blob/master/brownie/datastructures/mappings.py

    >>> d=ImmutableDict({"A":1})
    >>> d
    ImmutableDict({'A': 1})
    >>> d["A"] = 2
    Traceback (most recent call last):
        ...
    TypeError: 'ImmutableDict' objects are immutable
    """
    @classmethod
    def raise_immutable(cls, *args, **kwargs):
        raise TypeError('%r objects are immutable' % cls.__name__)

    __setitem__ = __delitem__ = setdefault = update = pop = popitem = clear = \
        raise_immutable

    def __repr__(self):
        content = dict.__repr__(self) if self else ''
        return '%s(%s)' % (self.__class__.__name__, content)

Vielleicht kann es noch jemand gebrauchen ;)

Re: ImmutableDict()

Verfasst: Montag 14. Juli 2014, 20:38
von EyDu
Ich würde noch die __hash__-Methode implementieren.