How to make an immutable instance

Batista, Facundo FBatista at uniFON.com.ar
Thu Jun 17 13:51:40 EDT 2004


I'm working on Decimal, and one of the PEP requests is Decimal to be
immutable.

The closer I got to that is (in short):

class C(object):

    __slots__ = ('__x',)

    def __init__(self, value):
        self.__x = value

    def getx(self):
        return self.__x

    x = property(getx)

This way, you can not modify the instance:

>>> import imm
>>> c = C(4)
>>> c.x
4
>>> c.x = 3

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in -toplevel-
    c.x = 3
AttributeError: can't set attribute
>>> c.a = 3

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in -toplevel-
    c.a = 3
AttributeError: 'C' object has no attribute 'a'
>>> hash(c)
10777424


The problem is that you actually could, if you take the effort, to rebind
the __x name. 

So, if you use this "immutable" class in a dict, and then you (on purpose)
modify it, you'll have different hashes.

Said that, how safer is this approach? Is there a better way?

Thank you all!

.	Facundo





. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
ADVERTENCIA  

La información contenida en este mensaje y cualquier archivo anexo al mismo,
son para uso exclusivo del destinatario y pueden contener información
confidencial o propietaria, cuya divulgación es sancionada por la ley. 

Si Ud. No es uno de los destinatarios consignados o la persona responsable
de hacer llegar este mensaje a los destinatarios consignados, no está
autorizado a divulgar, copiar, distribuir o retener información (o parte de
ella) contenida en este mensaje. Por favor notifíquenos respondiendo al
remitente, borre el mensaje original y borre las copias (impresas o grabadas
en cualquier medio magnético) que pueda haber realizado del mismo. 

Todas las opiniones contenidas en este mail son propias del autor del
mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones
Personales S.A. o alguna empresa asociada. 

Los mensajes electrónicos pueden ser alterados, motivo por el cual
Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación
cualquiera sea el resultante de este mensaje. 

Muchas Gracias.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20040617/bf57d67f/attachment.html>


More information about the Python-list mailing list