Making static dicts?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ognjen Bezanov

    #1

    Making static dicts?

    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?

    thanks,

    Ognjen.

  • Matimus

    #2
    Re: Making static dicts?

    On Jun 18, 1:46 pm, Ognjen Bezanov <Ogn...@mailsha ck.comwrote:
    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?
    >
    thanks,
    >
    Ognjen.
    How much functionality do you need? Something like this might work
    (though it could use better error messages.

    Code:
    class StaticDict:
    def __init__(self,srcdict):
    self._srcdict = srcdict
    def __getitem__(self,idx):
    return self._srcdict[idx]
    Use it like this:
    >>sd = StaticDict({'a' :'b'})
    >>sd['a']
    'b'
    >>sd['b']
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    File "<stdin>", line 5, in __getitem__
    KeyError: 'b'
    >>sd['a'] = "hello"
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    AttributeError: StaticDict instance has no attribute '__setitem__'
    >>>

    Comment

    • Steven D'Aprano

      #3
      Re: Making static dicts?

      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:

      Imagine you have a class like Coordinate that implements a two-dimensional coordinate pair. You might want to use instances of that class in...


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

      class ImmutableDict(d ict):
      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.

      Comment

      Working...