简体   繁体   中英

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?

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 )

You could pass a lambda expression as optional parameter:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM