Python callback function placeholders?
Asked Answered
J

1

7

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.
Japha answered 31/10, 2013 at 8:40 Comment(0)
L
7

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
Lunarian answered 31/10, 2013 at 8:42 Comment(1)
Aww, that was so fast. Thank you. I'm impressed. I think i have to wait 10 minutes to accept your answer lol. Btw, it worked like magic.Japha

© 2022 - 2024 — McMap. All rights reserved.