By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,520 Members | 1,766 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,520 IT Pros & Developers. It's quick & easy.

Unexpected result when comparing method with variable

P: n/a
I had a program fail on me today because the following didn't work as I
class C: .... def f(self):
.... pass
.... c = C()
m = c.f
m is c.f False

I would have expected that if I set a variable equal to a bound method, that
variable, for all intents and purposes, *is* that bound method, especially
since I hadn't changed or deleted anything on the class or its instance.

The same thing happens when attempting to compare an unbound method with a
variable name bound to that unbound method:
M = C.f
M is C.f


If I were to guess what is going on here, I would say that the expression
c.f invokes a descriptor that manufactures a brand new "method object" each
time. The problem is, this is non-intuitive (to me) and prevented me from
doing something I thought was useful.

My use case is deferring operations till later, by placing tuples of a
method and its arguments in a list to be processed at some future time, but
doing some special-case processing only for certain methods:

deferred = []
deferred.append((c.f, ('abc', 123)))


for method, params in deferred:
if method is c.f:
# handle a special case

But I can't do that special-case handling this way, I have to resort to some
other means to identify a method, "method is c.f" is always False. Which
seems strange to me.

This behavior is in Python 2.4, 2.3, and 2.2.

The workaround really awkward:

deferred.append((SPECIAL_METHOD, ('abc', 123)))
if method is SPECIAL_METHOD:
# handle special case

If I forget at any time to use the name SPECIAL_METHOD, but resort to it's
"real" name of c.f, then the comparison fails.

So, is this a bug or expected?

If I complain about this, would I get any sympathy? ;)

David H.

Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply

P: n/a
On Mon, 4 Apr 2005 23:34:41 -0400, David Handy
<da***> wrote:

I'm not sure if this is the best way. But it might work.
for method, params in deferred:
if method.im_func is c.f.im_func:
# handle a special case
if method is c.f:
# handle a special case


Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.