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

12,314

Solution 1

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 )

Solution 2

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.

Share:
12,314
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin about 2 years

    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?

  • Björn Pollex
    Björn Pollex almost 13 years
    If you bind a lambda to a name, you should make it a function in the first place.
  • RoundTower
    RoundTower almost 13 years
    well, using lambda does make it a function. But it's correct to say you should just use def in this case. The first line is exactly equivalent to def mondayCond(today): return isMonday(today)
  • SirDarius
    SirDarius almost 13 years
    Your lambdas need to take the same arguments in order for copy_func to use them. Probably they should both take the filename (x), and isMonday would just ignore it and get today itself (not from the arg)
  • Artsiom Rudzenka
    Artsiom Rudzenka almost 13 years
    Thank you all -i understand where i was wrong and modified my answer
  • Artsiom Rudzenka
    Artsiom Rudzenka almost 13 years
    @RoundTower but why i should use def if i simply want to use oneline function?
  • Björn Pollex
    Björn Pollex almost 13 years
    @Artsiom: This excellent answer from the awesome Alex Martelli explains it very well (among other things).
  • Artsiom Rudzenka
    Artsiom Rudzenka almost 13 years
    @Space_C0wb0y - thank you , will take a look and try to avoid creating such methods in a future
  • Georgy
    Georgy almost 5 years
    Another option is to use operator.methodcaller: the_exe_rule = methodcaller('endswith', 'exe'). You can add it in your answer if you want