Unexpected result when comparing method with variable

David Handy david at handysoftware.com
Mon Apr 4 23:57:12 EDT 2005


On Tue, Apr 05, 2005 at 03:38:09PM +1200, Tony Meyer wrote:
> [David Handy]
> > I had a program fail on me today because the following didn't 
> > work as I expected:
> > 
> > >>> class C:
> > ...     def f(self):
> > ...         pass
> > ...
> > >>> c = C()
> > >>> m = c.f
> > >>> m is c.f
> > False
> [...]
> > The workaround really awkward:
> 
> What's wrong with this?
> 
> >>> class C:
> ... 	def f(self):
> ... 		pass
> ... 	def g(self):
> ... 		pass
> ... 	
> >>> c = C()
> >>> m = c.f
> >>> m == c.f
> True
> >>> m == c.g
> False

Nothing is wrong with that, I just (blush) didn't think to try == instead of
"is".

Since == works, that also means that using a method as a key to a dictionary
also works reliably:

>>> d = {c.f: 'special case 1'}
>>> d[c.f]
'special case 1'

So I have no more complaints, other than I expected "is" to work and it
didn't...but I can do what I want and it isn't awkward, so  I'll just go
back in my hole now...

Thanks,
David H.




More information about the Python-list mailing list