Unexpected result when comparing method with variable

D

David Handy

I had a program fail on me today because the following didn't work as I
expected:
.... def f(self):
.... pass
....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:
False

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:
method(*params)
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:

SPECIAL_METHOD = c.f
....
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? ;)

regards,
David H.
 
R

Ron_Adam

On Mon, 4 Apr 2005 23:34:41 -0400, David Handy

I'm not sure if this is the best way. But it might work.


for method, params in deferred:
method(*params)
try:
if method.im_func is c.f.im_func:
# handle a special case
except:
if method is c.f:
# handle a special case



Cheers,
Ron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top