Design thought for callbacks
Cem Karan
cfkaran2 at gmail.com
Tue Feb 24 06:06:33 EST 2015
I'm combining two messages into one,
On Feb 24, 2015, at 12:29 AM, random832 at fastmail.us wrote:
> On Tue, Feb 24, 2015, at 00:20, Gregory Ewing wrote:
>> Cem Karan wrote:
>>> I tend to structure my code as a tree or DAG of objects. The owner refers to
>>> the owned object, but the owned object has no reference to its owner. With
>>> callbacks, you get cycles, where the owned owns the owner.
>>
>> This is why I suggested registering a listener object
>> plus a method name instead of a callback. It avoids that
>> reference cycle, because there is no long-lived callback
>> object keeping a reference to the listener.
>
> How does that help? Everywhere you would have had a reference to the
> "callback object", you now have a reference to the listener object.
> You're just shuffling deck chairs around: if B shouldn't reference A
> because A owns B, then removing C from the B->C->A reference chain does
> nothing to fix this.
On Feb 24, 2015, at 12:45 AM, Gregory Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Cem Karan wrote:
>> On Feb 22, 2015, at 5:15 AM, Gregory Ewing <greg.ewing at canterbury.ac.nz>
>> wrote:
>>> Perhaps instead of registering a callback function, you should be
>>> registering the listener object together with a method name.
>> I see what you're saying, but I don't think it gains us too much. If I store
>> an object and an unbound method of the object, or if I store the bound method
>> directly, I suspect it will yield approximately the same results.
>
> It would be weird and unpythonic to have to register both
> an object and an unbound method, and if you use a bound
> method you can't keep a weak reference to it.
Greg, random832 said what I was thinking earlier, that you've only increased the diameter of your cycle without actually fixing it. Can you give a code example where your method breaks the cycle entirely?
Thanks,
Cem Karan
More information about the Python-list
mailing list