Design thought for callbacks

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Feb 23 08:31:05 EST 2015


Cem Karan wrote:

> 
> On Feb 21, 2015, at 12:27 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:

>> The simplest possible identity-based scheme would be something like this:
>> 
>> 
>> # don't hate me for using a global variable
>> CALLBACKS = []
>> 
>> def register(func):
>>    if func not in CALLBACKS:
>>         CALLBACKS.append(func)
>> 
>> def unregister(func):
>>    try:
>>        CALLBACKS.remove(func)
>>    except ValueError:
>>        pass

Oops! That's not identity-based, that's *equality* based.

Both the `in` operator and the list `remove` method implicitly perform
equality checks, not identity checks. Which means that they will work with
methods, since method equality compares against the underlying function,
which is the same:


py> class Spam(object):
...     def method(self):
...             pass
...
py> s = Spam()
py> a = s.method
py> b = s.method
py> a is b
False
py> a == b
True
py> a.__func__ is b.__func__
True


So, when I say this:

>> That's probably a bit too simple, since it won't behave as expected with
>> bound methods. The problem is that bound methods are generated on the
>> fly, so this won't work:

I was mistaken.


> Are you sure about that?  I just tested out the following code, and it
> appears to work correctly:

You are correct.



-- 
Steven




More information about the Python-list mailing list