Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an 'if' statement to a function?

I want to pass an optional 'if' statement to a Python function to be executed. For example, the function might copy some files from one folder to another, but the function could take an optional condition.

So, for example, one call to the method could say "copy the files from source to dest if source.endswith(".exe")

The next call could be simply to copy the files from source to destination without condition.

The next call could be to copy files from source to destination if today is monday

How do you pass these conditionals to a function in Python?

like image 677
shoes_for_news Avatar asked Dec 01 '22 02:12

shoes_for_news


1 Answers

Functions are objects. It's just a function that returns a boolean result.

def do_something( condition, argument ):
   if condition(argument):
       # whatever

def the_exe_rule( argument ):
    return argument.endswith('.exe')

do_something( the_exe_rule, some_file )

Lambda is another way to create such a function

do_something( lambda x: x.endswith('.exe'), some_file )
like image 170
S.Lott Avatar answered Dec 04 '22 11:12

S.Lott