Are instances of user-defined classes mutable?
Richard Damon
Richard at Damon-Family.org
Thu Aug 6 11:17:57 EDT 2020
On 8/6/20 10:40 AM, Robin Becker wrote:
> On 06/08/2020 05:17, ZHAOWANCHENG wrote:
>> the doc of dictionary said "if a tuple contains any mutable object
>> either directly or indirectly, it cannot be used as a key."
>> i think a instance of user-defined class is mutable, but i found it
>> can be placed into a tuple that as a key of a dict:
>> >>> class mycls(object):
>> ... a = 1
>> ...
>> >>> me = mycls()
>> >>> me.a = 2 # mutable?
>> >>> {(1, me): 'mycls'}
>> {(1, <__main__.mycls object at 0x0000022824DAD668>): 'mycls'}
>> >>>
>>
>>
>> So are instances of user-defined classes mutable or immutable?
>>
> user class instances are clearly mutable, and in my python 3.8 you can
> do horrid things like this
But since the 'mutation' doesn't affect the hash or the equality tests
on the object, is it really a mutation?
>
>>>>> class H:
>> ... a = 1
>> ... def __hash__(self):
>> ... return hash(self.a)
>> ...
>>>>> h = H()
>>>>> hash(h)
>> 1
>>>>> h.a =2
>>>>> hash(h)
>> 2
>>>>> t=(1,h)
>>>>> d={t:23}
>>>>> d
>> {(1, <__main__.H object at 0x7f5bf72021f0>): 23}
>>>>> hash(h)
>> 2
>>>>> hash(list(d.keys())[0])
>> -3550055125485641917
>>>>> h.a=33
>>>>> hash(list(d.keys())[0])
>> -3656087029879219665
>>>>>
> so the dict itself doesn't enforce immutability of its keys
Yes, here you have defined a hash that violates the requirements of the
Dictionary (and most things that use hashes) so your class is broken,
and you can expect to get strangeness out of your dictionary.
> --
> Robin Becker
>
--
Richard Damon
More information about the Python-list
mailing list