Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

python - How should functions be tested for equality or identity?

I would like to be able to test whether two callable objects are the same or not. I would prefer identity semantics (using the "is" operator), but I've discovered that when methods are involved, something different happens.

#(1) identity and equality with a method
class Foo(object):
    def bar(self):
        pass
foo = Foo()
b = foo.bar
b == foo.bar    #evaluates True. why?
b is foo.bar    #evaluates False. why?

I've reproduced this with both Python 2.7 and 3.3 (CPython) to make sure it's not an implementation detail of the older version. In other cases, identity testing works as expected (interpreter session continued from above):

#(2) with a non-method function
def fun(self):
    pass
f = fun
f == fun    #evaluates True
f is fun    #evaluates True

#(3) when fun is bound as a method 
Foo.met = fun
foo.met == fun    #evaluates False
foo.met is fun    #evaluates False

#(4) with a callable data member
class CanCall(object):
    def __call__(self):
        pass
Foo.can = CanCall()
c = foo.can
c == foo.can    #evaluates True
c is foo.can    #evaluates True

According to the question How does Python distinguish callback function which is a member of a class?, a function is wrapped when bound as a method. This makes sense and is consistent with case (3) above.

Is there a reliable way to bind a method to some other name and then later have them compare equal like a callable object or a plain function would? If the "==" does the trick, how does that work? Why do "==" and "is" behave differently in case (1) above?

Edit

As @Claudiu pointed out, the answer to Why don't methods have reference equality? is also the answer to this question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Python doesn't keep a canonical foo.bar object for every instance foo of class Foo. Instead, a method object is created when Python evaluates foo.bar. Thus,

foo.bar is not foo.bar

As for ==, things get messy. Python 3.8 fixed method comparison so two methods are equal if they represent the same method of the same object, but on lower versions, the behavior is inconsistent.

Python has a surprisingly large number of method object types, depending on whether the method was implemented in Python or one of the several ways methods can be implemented in C. Before Python 3.8, these method object types respond to == differently:

  • For methods written in Python, == compares the methods' __func__ and __self__ attributes, returning True if the method objects represent methods implemented by the same function and bound to equal objects, rather than the same object. Thus, x.foo == y.foo will be True if x == y and foo is written in Python.
  • For most "special" methods (__eq__, __repr__, etc.), if they're implemented in C, Python compares __self__ and an internal thing analogous to __func__, again returning True if the methods have the same implementation and are bound to equal objects.
  • For other methods implemented in C, Python does what you'd actually expect, returning True if the method objects represent the same method of the same object.

Thus, if you run the following code on a Python version below 3.8:

class Foo(object):
    def __eq__(self, other):
        return True if isinstance(other, Foo) else NotImplemented
    def foo(self):
        pass

print(Foo().foo == Foo().foo)
print([].__repr__ == [].__repr__)
print([].append == [].append)

You get the following bizarre output:

True
True
False

To get the Python 3.8 semantics on lower versions, you can use

meth1.__self__ is meth2.__self__ and meth1 == meth2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...