How to pass an if statement to a function?

I want to pass an optional if statement to Python functions to execute. For example, a function may copy some files from one folder to another, but a function may accept an optional condition.

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

The next call may simply be to copy files from the source to the destination without any conditions.

The next call might be copying files from source to destination, if today is monday

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

+4
source share
3 answers

Functions are objects. This is just a function that returns a logical 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 ) 
+14
source

You can pass the lambda expression as an optional parameter:

 def copy(files, filter=lambda unused: True): for file in files: if filter(file): # copy 

lambda always returns true by default, so if no condition is specified, all files are copied.

+5
source

I think you can use something like this:

 def copy_func(files, destination, condition=None): for fileName in files: if condtition is None or condition(fileName): #do file copy copy_func(filesToCopy, newDestionation) # without cond copy_func(filesToCopy, newDestionation, lambda x: x.endswith('.exe')) # with exe cond 
0
source

All Articles