How to pass an 'if' statement to a function?
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.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on June 04, 2022Comments
-
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 almost 13 yearsIf you bind a
lambda
to a name, you should make it a function in the first place. -
RoundTower almost 13 yearswell, using
lambda
does make it a function. But it's correct to say you should just usedef
in this case. The first line is exactly equivalent todef mondayCond(today): return isMonday(today)
-
SirDarius almost 13 yearsYour 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 almost 13 yearsThank you all -i understand where i was wrong and modified my answer
-
Artsiom Rudzenka almost 13 years@RoundTower but why i should use def if i simply want to use oneline function?
-
Björn Pollex almost 13 years@Artsiom: This excellent answer from the awesome Alex Martelli explains it very well (among other things).
-
Artsiom Rudzenka almost 13 years@Space_C0wb0y - thank you , will take a look and try to avoid creating such methods in a future
-
Georgy almost 5 yearsAnother option is to use
operator.methodcaller
:the_exe_rule = methodcaller('endswith', 'exe')
. You can add it in your answer if you want