Returning a list/dict as "read-only" from a method ?
Sean Ross
sross at connectmail.carleton.ca
Thu Dec 26 13:34:39 EST 2002
or, you might try this:
class ReadOnlyDict(dict):
def __setitem__(self, key, value):
self.setdefault(key, value)
def update(self, _dict):
for key, val in _dict.items():
self[key] = val
This subclass of dict will allow full access, but modification is restricted
to adding new key, value pairs.
For instance,
m = ReadOnlyDict()
m['hello'] = 'world'
m['you'] = 'me'
m['hello'] = 'universe'
for key in m:
print "m[%s]: %s" % (key, m[key])
will give you:
m[you]: me
m[hello]: world
and,
b = {'hello':'universe', 'hey':'there'}
m.update(b)
for key in m:
print "m[%s]: %s" % (key, m[key])
will give you:
m[hey]: there
m[you]: me
m[hello]: world
You'll notice that I did not raise an Exception when trying to modify an
existing key's value.
You probably should raise one in __setitem__():
def __setitem__(self, key, value):
if not self.setdefault(key, value) == value:
raise Exception("Error: ReadOnlyDict attributes cannot be
modified")
(Note: if you don't want to allow people to add new key, value pairs, then
you'll need to make a constructor
and __setitem__() and update() should probably raise exceptions whenever
they are called)
ok. hope that's useful,
sean
More information about the Python-list
mailing list