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?
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With