Making static dicts?
Matimus
mccredie at gmail.com
Mon Jun 18 18:31:40 EDT 2007
On Jun 18, 1:46 pm, Ognjen Bezanov <Ogn... at mailshack.com> 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?
>
> 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]
[/code]
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__'
>>>
More information about the Python-list
mailing list