pythoncallbackclosurespartial-application

I need to provide a callback when instantiating a class from an API. How can I bind the instance itself to the callback, eagerly?


I've encountered this problem with a few different major third-party libraries and frameworks now. Let me try to boil it down to the essentials:

Thus, I would like to bind x as an argument to modify, per Python Argument Binders. The problem is, it doesn't exist yet, because I am still calling the constructor:

>>> from functools import partial
>>> x = Example(callback=partial(modify, x))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Of course, I could avoid the NameError by allowing the lambda to look up the name later:

>>> x = Example(callback=lambda: modify(x))

but this is late binding, so it doesn't work properly if e.g. I'm in a loop and instance is the iteration variable, or if instance is reassigned later for any other reason.

How can I accomplish early binding of instance to its own callback?


Solution

  • Generally, you can try any of these approaches: