Question

I want to add a callback function to list which will cause the callback to be called with one parameter at the appropriate time. However, I also want the callback to be passed another variable as well.

Note: I am used to std::bind or boost::bind in c++, so i was looking for something like that.

Note: This is in Python by the way.

Example of problem with collisions:

def collision_callback(hit, hitter)
     # doing something relevant...

object = create_object()
collision_callbacks.append(collision_callback(_1, object)) # _1 is a placeholder from C++ lol.
                                                      # as you can see here _1 is expected
                                                      # to be filled in with the hit object.
Was it helpful?

Solution

You can use lambda:

>>> def minus(a, b):
...     return a - b
... 
>>> minus1 = lambda x: minus(x, 1)
>>> minus1(3)
2

Alternatively, you can also use functools.partial:

>>> minus1 = functools.partial(minus, b=1)
>>> minus1(4)
3

But some builtin functions do not accept keyword arguments. Then fall back to lambda.

>>> print(operator.sub.__doc__)
sub(a, b) -- Same as a - b.
>>> minus1 = functools.partial(operator.sub, b=1)
>>> minus1(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sub() takes no keyword arguments

>>> minus1 = lambda x: operator.sub(x, 1)
>>> minus1(9)
8

If you prefill the leading parameters (fill values from the first parameter), this doesn't matter:

>>> minus_from_10 = functools.partial(operator.sub, 10)
>>> minus_from_10(7)
3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top