how to test for atomicity/mutability/hashability?

Chris Rebert clp2 at rebertia.com
Thu Oct 7 16:55:10 EDT 2010


On Thu, Oct 7, 2010 at 1:46 PM, Arnaud Delobelle <arnodel at gmail.com> wrote:
> kj <no.email at please.post> writes:
>> I want to implement a test t() that will return True if its two
>> arguments are "completely" different.  By this I mean that they
>> don't share any "non-atomic" component.  E.g., if
>>
>> a = [0, 1]
>> b = [0, 1]
>> c = [2, 3]
>> d = [2, 3]
>>
>> A = (a, c, 0)
>> B = (a, d, 1)
>> C = (b, d, 0)
>>
>> The desired test t() would yield:
>>
>> t(A, B) -> False (A and B share the mutable component a)
>> t(A, C) -> True (a =!= c, b =!= d, and 0 is not mutable)
>> t(B, C) -> False (B and C share the mutable component d)
>>
>> (=!= is shorthand with "is not identical to".)
>>
>> It would facilitate the implementation of t() to have a simple test
>> for mutability.  Is there one?
>>
>> Thanks!
>>
>> ~kj
>
> I think defining mutability is subject to opinion, but here is a first
> approximation.
>
>
> def mutable(obj):
>    return obj.__hash__ is None or type(obj).__hash__ == object.__hash__

Corner case (I think):
>>> a = object()
>>> a.b = "c"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'b'
>>> mutable(a)
True

Cheers,
Chris



More information about the Python-list mailing list