Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing multiple functions as arguments to another function anonymously Python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading