I would like to implement an immutable type in python natively. I gathered from here
How to make an immutable object in Python?
that the best way is to override tuple. Let's say I want a tuple that stores some extra data. I would do something like:
class MyTuple(tuple):
def __new__(cls, lst, data):
return tuple.__new__(cls, tuple(lst) + (data, ))
Now I would like to override the len function:
def __len__(self):
return tuple.__len__(self) - 1
This worked fine with my python version at home (Python 2.something, but I don't know which), but on my office computer (Python 2.7.3) it breaks slicing: If I do
m = MyTuple([1,2], 0)
print(m[:-1])
I get (1, )
while at home I would get (1, 2)
(I didn't actually check, but tracing my problem back to this minimal example, I think so). So it seems in one implementation, slicing is calling tuple.__len__
while in the other it is calling MyTuple.__len__
. I wouldn't mind either way, but consistency would be good.
So my question is: is there a robust solution and if not, which of the behaviors is going to be the stable one?
Edit: as Leonardo.Z suggested, my "home" python was actually Python 3(.4). I had been trying a new ide and not paid attention to which Python it used.