[Tutor] Immutable objects
Alan Gauld
alan.gauld at btinternet.com
Thu Aug 19 10:46:48 CEST 2010
"Nitin Das" <nitin.162 at gmail.com> wrote
> class mymut(object):
>
> def __setattr__(self,k,v):
> if hasattr(self,k):
> if self.__dict__.get(k) == None:
> self.__dict__[k] = v
Do you need to look up the dict?
Surely you could just use
if self.k is None
self.k = v
which looks a lot simpler to me...
> else:
> raise TypeError("Cant Modify Attribute Value")
You could mention the class for example.
Compare it with the string and tuple messages:
>>> 'fred'[2] = 'g'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> (1,2,30)[1] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
So if your error said
TypeError: mymut object does not support item assignment
that would be more consistent with the Python internal objects.
> else:
> raise TypeError("Immutable Object")
The Python immutables seem to raise an Attribute Error here
rather than a Type error. And again mentioning the class name
makes debugging easier:
>>> 'l'.x = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'x'
>>>
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list