Making static dicts?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon Jun 18 19:40:03 EDT 2007


On Mon, 18 Jun 2007 21:46:23 +0100, Ognjen Bezanov wrote:

> Hello!
> 
> Just to ask, is it possible to make a static dictionary in python. So 
> that the keys in the dictionary cannot be removed, changed or new ones 
> added, but the value pairs can.
> 
> Is this possible with python?


I'm sure it is possible, but you'll have to program it yourself.

The usual term for what you are describing is "immutable" rather than
static. For some ways of making an immutable class, see here:

http://northernplanets.blogspot.com/2007/01/immutable-instances-in-python.html

To get the dictionary behaviour, the easiest ways would be either to
sub-class from dict:

class ImmutableDict(dict):
    pass

or perhaps use delegation (google on "Python automatic delegation" for
more information). 

You might like to look at the source code for the UserDict module in the
standard library for some ideas (especially the DictMixin class).

I leave putting these pieces together into a working immutable dictionary
up to you. Good luck!


-- 
Steven.




More information about the Python-list mailing list