Skip to content Skip to sidebar Skip to footer

Wrap Callback Function To Include Extra Argument When Caller Verifies Exact Callback Signature

I'm trying to bind multiple callback functions across multiple properties with code that looks something like: for key in keys: def callback(self, value): #Do stuff...

Solution 1:

I would create a callback generator that takes your parameters (such as key) and creates your callbacks.

>>> def callback_generator(key):
...     def callback(self, value):
...         do_something_with(key, value)
...     return callback
...
>>> for key in keys:
...     doSomething(callback_generator(key))
...

Solution 2:

Minutes after I figured out that I can create a function inside the for loop to get a new stack frame. This unfortunately does not seem at all Pythonic...

for key in keys:
    def dummyForStackFrame(key): #Extra function to get a new stack frame with key
        def wrappedCallback(self, value):
            realCallback(self, key, value)
            return None
        doSomething(wrappedCallback
    dummyForStackFrame(key)

Post a Comment for "Wrap Callback Function To Include Extra Argument When Caller Verifies Exact Callback Signature"