shoes_for_news
shoes_for_news

Reputation: 43

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?

Upvotes: 4

Views: 21225

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

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

Upvotes: 0

Björn Pollex
Björn Pollex

Reputation: 76788

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.

Upvotes: 5

S.Lott
S.Lott

Reputation: 391854

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 )

Upvotes: 14

Related Questions