[Python-Dev] Equality on method objects
Phillip J. Eby
pje at telecommunity.com
Mon Mar 10 00:05:12 CET 2008
At 01:59 PM 3/9/2008 -0800, Guido van Rossum wrote:
>Do we have much of a use case for this?
I've often had APIs that take a callback that promise to only invoke
the callback once, even if it's added more than once. And I've used
dicts, lists, and sets for same.
I did not, however, need the equality of bound methods to be based on
object value equality, just value identity.
...at least until recently, anyway. I do have one library that wants
to have equality-based comparison of im_self. What I ended up doing
is writing code that tests what the current Python interpreter is
doing, and if necessary implements a special method type, just for
purposes of working around the absence of im_self equality
testing. However, it's a pretty specialized case, and if I didn't
have to support older Python versions I'd just use partial() --
assuming that partial() supports hashing and equality comparisons,
that is, which I haven't checked. I imagine hashing a partial()
might be at least as tricky as getting bound methods "right". :)
>That said, if there's a use case, I agree that it would be okay with
>basing the equality of x.foo and y.foo on whether x and y are the same
>object, not on whether x==y (consider 0 .__add__ == 0.0 .__add__).
+1 for making two bound methods m1 and m2 equal if and only if
"m1.im_self is m2.im_self and m1.im_func==m2.im_func", and making the
hash based on im_func and id(im_self).
I don't think that the im_func comparison should be identity-based by
default, however. (The im_func could be another bound method, for example.)
More information about the Python-Dev
mailing list