Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python callback function placeholders?

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.
like image 596
user2940623 Avatar asked Oct 31 '13 08:10

user2940623


People also ask

How do you use a placeholder in Python?

In Python, you can use {} as placeholders for strings and use format() to fill in the placeholder with string literals. For example: print("You have {} apples.". format(5)) # this will print: # You have 5 apples.

What is the placeholder in Python?

In Python, Placeholder is a word, characters or a string of characters to hold a temporary place. The placeholder behaves as a dynamic place holder in such a way that you can pass a particular value for that placeholder.

Which keyword is used as a placeholder in Python?

Python pass Statement The pass statement is used as a placeholder for future code.

What is callback in Python?

In Python, a callback is simply a function or a method passed to LocalSolver. A callback takes two parameters: the LocalSolver object that triggers the event and the type of the callback. It is possible to use the same callback method or object for multiple events or multiple LocalSolver instances.


1 Answers

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
like image 112
falsetru Avatar answered Sep 19 '22 17:09

falsetru