Possible constant assignment operators ":=" and "::=" for Python
Michele Simionato
michele.simionato at gmail.com
Fri May 5 03:12:14 EDT 2006
Edward Elliott wrote:
> Michele Simionato wrote:
> >> >>> A = [] # let's declare a "constant" here
> >> >>> b = A # and let's assign the constant here
> >> >>> b.append('1') # OOPS!
> >
> > But it makes no sense to use a mutable object for a constant!
> > The user should use a tuple,
>
> Sure. Now show me the builtin immutable equivalent of a dict.
There is none. However it is pretty easy to get one:
import UserDict
class ReadOnlyDict(UserDict.DictMixin):
def __init__(self, dic):
self._dic = dic
def __getitem__(self, name):
return self._dic[name]
def keys(self):
return self._dic.keys()
def __getitem__(self, name):
raise TypeError('this dictionary is read-only')
def __delitem__(self, name):
raise TypeError('this dictionary is read-only')
I am sure you already know that, this snipped is for the benefit of the
other
readers of this thread. Of course, the ReadOnlyDict can be modified by
modifying ._dic, but the point was all about avoiding accidental
modifications.
> > or a custom list-like type where
> > all methods with side effects are removed, so it effectively acts
> > as a tuple.
>
> Ugh, not worth the trouble imo.
Agreed, use a tuple if you need a tuple.
Michele Simionato
More information about the Python-list
mailing list