Supply condition in function call

Gary Herron gherron at digipen.edu
Wed Mar 25 15:13:14 EDT 2015


On 03/25/2015 10:29 AM, Manuel Graune wrote:
> Hi,
>
> I'm looking for a way to supply a condition to an if-statement inside a
> function body when calling the function. I can sort of get what I want
> with using eval (see code below) but I would like to achieve this in a
> safer way. If there is a solution which is safer while being
> less flexible, that would be fine. Also, supplying the condition as a
> string is not necessary. What I want to do is basically like this:
>
> def test1(a, b, condition="True"):
>      for i,j in zip(a,b):
>          c=i+j
>          if eval(condition):
>             print("Foo")
>
> test1([0,1,2,3],[1,2,3,4],"i+j >4")
> print("Bar")
> test1([0,1,2,3],[1,2,3,4],"c >4")
> print("Bar")
> test1([0,1,2,3],[1,2,3,4],"a[i] >2")
> print("Bar")
> test1([0,1,2,3],[1,2,3,4])
>
>

This is nicely done with lambda expressions:

To pass in a condition as a function:
    test1([0,1,2,3],[1,2,3,4], lambda i,j: i+j<4)

To check the condition in the function:
     if condition(i,j):

To get the full range of conditions, you will need to include all the variables needed by any condition you can imagine.  So the above suggestions may need to be expanded to:
  ... lambda i,j,a,b: ... or whatever

and
   ... condition(i,j,a,b) ... or whatever

If any of your conditions gets too long/complex for a lambda (or you just don't like Python's lambda expressions), then just create a function for your condition:

   def cond1(i,j,a,b):
       return i+j>4

and do
    test1(..., cond1)
and
     if condition(i,j,a,b):




-- 
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418




More information about the Python-list mailing list