I have code in PHP that I would like to rewrite in Python, but the difficulty is passing functions as arguments. Here is the PHP code:
function s($t1, $t2, ...$funcs){
echo '$t1' . PHP_EOL;
echo '$t2' . PHP_EOL;
foreach ($funcs as $func)
$func();
unset($func);
}
It is important to me that the transfer method does not require a preliminary declaration of functions:
s('a', 'b', function(){print(5);}, function() {print(6);});
The question is what is the best way to implement this in python?
I tried to do the same in Python as in PHP, but without success:
s('a', 'b', partial(print, 5))
Also, I’m not sure if this is the best solution to the problem.
>Solution :
Your PHP code adapts to python quite literally:
def s(t1, t2, *funcs):
print(t1)
print(t2)
for func in funcs:
func()
Note how python’s * replaces PHP’s ... for variable number of arguments.
You can use the lambda keyword to declare anonymous inline functions:
s('a', 'b', lambda: print(5), lambda: print(6))
# a
# b
# 5
# 6
You can also use functools.partial, although this is rarely the best way to do things in python in my opinion:
from functools import partial
s('a', 'b', partial(print, 5), partial(print, 6))
# a
# b
# 5
# 6