RV: How to make an immutable instance

Batista, Facundo FBatista at uniFON.com.ar
Tue Jun 22 09:06:54 EDT 2004


Thank you for your assistance.

I'll go in Decimal with a solution with property() and *single* underscore:

class C(object): 

    __slots__ = ('_x',) 

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

    def getx(self): 
        return self._x 

    x = property(getx)


This implies good security against accidental changes and saves me from a
*lot* (a lot!) of code changing in Decimal.py

Thanks again.

Facundo Batista
Desarrollo de Red
fbatista at unifon.com.ar
(54 11) 5130-4643
Cel: 15 5097 5024




-----Mensaje original-----
De: Batista, Facundo 
Enviado el: Jueves 17 de Junio de 2004 2:52 PM
Para: Python-List (E-mail)
Asunto: How to make an immutable instance


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. 




More information about the Python-list mailing list