Außer dem Fakt, dass wenn du sowohl `data` als auch `oldfoo` angibst, `oldfoo` keine Wirkung hat eigentlich nichts.
Ich mache es jedoch etwas anders:
Code: Alles auswählen
class Table(dict):
"""Simplified version of frozendict from
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/414283
This implementation is not hashable nor does it try to be.
It is meant to be used as a drop-in replacement for 'dict'
and throws AttributeErrors when trying to change it.
Do not expect absolute security from this code, it is only
meant to catch errors when one mistakenly alters keys in
this object instead of creating a new Table object based
on this one.
To create a new Table based on this one use
>>> Table(old_table, new_key='new_value')
>>> # or
>>> Table(old_table, { 'new_key' : 'new_value' })"""
def _blocked_attribute(obj):
"""This is called when trying to access a attribute which
modifies the state of this object"""
# blocked, complain
raise AttributeError("A Table cannot be modified")
# turn _blocked_attribute into a property
_blocked_attribute = property(_blocked_attribute)
# overwrite modifying methods with _blocked_attribute
__delitem__ = __setitem__ = clear = _blocked_attribute
pop = popitem = setdefault = update = _blocked_attribute
def __repr__(self):
"""Display the contents of the Table"""
return "Table(%s)" % dict.__repr__(self)
def update(table, updates, *args, **kwargs):
"""Updates a Table environment - it does not alter the Table,
instead it returns a new Table with the changes applied"""
# create a new empty dictionary to hold all values
new_table = dict()
# choin both dict-like objects together
all_items = itertools.chain(table.iteritems(), updates.iteritems())
# add all keys to the dictionary
for key, value in all_items:
new_table[key] = value
# convert the dictionary into a Table and return
return Table(new_table)
Damit habe ich eine Klasse, die immutable ist und die bei update() eine neue Klasseninstanz ausgibt, die eine aktualisierte Kopie seiner selbst zurückgibt.