A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2012-March/117161.html below:

[Python-Dev] Add a frozendict builtin type

[Python-Dev] Add a frozendict builtin typeSerhiy Storchaka storchaka at gmail.com
Thu Mar 1 14:44:18 CET 2012
01.03.12 11:11, Victor Stinner написав(ла):
>> You can redefine dict.__setitem__.
> Ah? It doesn't work here.
>
>>>> dict.__setitem__=lambda key, value: None
> Traceback (most recent call last):
>    File "<stdin>", line 1, in<module>
> TypeError: can't set attributes of built-in/extension type 'dict'

Hmm, yes, it's true. It was too presumptuous of me to believe that you 
have not considered such simple approach.

But I will try to suggest another approach. `frozendict` inherits from 
`dict`, but data is not stored in the parent, but in the internal 
dictionary. And even if dict.__setitem__ is used, it will have no 
visible effect.

   class frozendict(dict):
       def __init__(self, values={}):
           self._values = dict(values)
       def __getitem__(self, key):
           return self._values[key]
       def __setitem__(self, key, value):
           raise TypeError ("expect dict, got frozendict")
       ...


  >>> a = frozendict({1: 2, 3: 4})
  >>> a[1]
  2
  >>> a[5]
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 5, in __getitem__
  KeyError: 5
  >>> a[5] = 6
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 7, in __setitem__
  TypeError: expect dict, got frozendict
  >>> dict.__setitem__(a, 5, 6)
  >>> a[5]
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 5, in __getitem__
  KeyError: 5

More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4