473,395 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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.

Jul 18 '05 #1
4 1270
Batista, Facundo wrote:
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) 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.
I don't think this will be a problem in practice. If you are determined,
there are easier ways to break your program :-)
Said that, how safer is this approach? Is there a better way?
An alternative would be to subclass tuple:
class C(tuple): .... def __new__(cls, x):
.... return tuple.__new__(cls, (x,))
.... x = property(lambda self: self[0])
.... c = C(1)
c.x 1

Not necessarily better, as
isinstance(c, tuple)

True

and a Decimal pretending to be a sequence type may cause greater
inconveniences than the "weak immutability" you currently have.
Thank you all!


Thank you for your work to further improve Python.

Peter

Jul 18 '05 #2
Batista, Facundo wrote:
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?


The best I know of is this:
class Foo(object):
__slots__ = ('x',)

# __new__ is used instead of __init__ so that no one can call
# __new__ directly and change the value later.
def __new__(cls, value):
self = object.__new__(cls)
self.x = value
return self

def __setattr__(self, attr, value):
if attr in self.__slots__ and not hasattr(self, attr):
object.__setattr__(self, attr, value)
else:
raise AttributeError, "This object is immutable."
But note that you can still use object.__setattr__ directly to get
around it. I don't think there's a way to get true immutability in pure
Python.
Jul 18 '05 #3
In article <2j*************@uni-berlin.de>,
Leif K-Brooks <eu*****@ecritters.biz> wrote:
Batista, Facundo wrote:

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?


[...]

But note that you can still use object.__setattr__ directly to get
around it. I don't think there's a way to get true immutability in pure
Python.


Correct. Remember that Python is a language for consenting adults; the
only way to guarantee object immutability is to create a type in C.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py
Jul 18 '05 #4
"Batista, Facundo" <FB******@uniFON.com.ar> writes:
I'm working on Decimal, and one of the PEP requests is Decimal to be
immutable.
[...]
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?


I'd say it's safe enough. It's going to be impossible to guard
against all malicious code, so you should aim to prevent accidents.

Cheers,
mwh

--
I also feel it essential to note, [...], that Description Logics,
non-Monotonic Logics, Default Logics and Circumscription Logics
can all collectively go suck a cow. Thank you.
-- http://advogato.org/person/Johnath/diary.html?start=4
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Zalek Bloom | last post by:
I am learning about difference between String and StringBuffer classes. In a book it sayes that a String class is immutable, that means that one an instance of String class is created, the string...
0
by: Batista, Facundo | last post by:
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 =...
6
by: Mapisto | last post by:
Hi, I've noticed that if I initialize list of integers in the next manner: >>> my_list = * 30 It works just fine, even if I'll try to assign one element: >>> id( my_list ) 10900116
48
by: Andrew Quine | last post by:
Hi Just read this article http://www.artima.com/intv/choices.html. Towards the end of the dicussions, when asked "Did you consider including support for the concept of immutable directly in C#...
90
by: Ben Finney | last post by:
Howdy all, How can a (user-defined) class ensure that its instances are immutable, like an int or a tuple, without inheriting from those types? What caveats should be observed in making...
3
by: Sam Kong | last post by:
Hi group, I want to have some advice about immutable objects. I made a constructor. function Point(x, y) { this.x = x; this.y = y; }
16
by: fallenidol | last post by:
how do you create an immutable object in c#? thanks in advance
16
by: InDepth | last post by:
Now that .NET is at it's fourth release (3.5 is coming soon), my very humble question to the gurus is: "What have we won with the decision to have string objects immutable? Or did we won?" ...
4
by: bbawa1 | last post by:
What does the term immutable mean? Could you please explain me with examples.
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.