On Wed, Mar 25, 2015 at 11:29 AM, Manuel Graune <manuel.gra...@koeln.de> 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")
Pass the condition as a function. def test1(a, b, condition=lambda i, j: True): for i,j in zip(a,b): c=i+j if condition(i, j): print("Foo") test1([0,1,2,3],[1,2,3,4], lambda i, j: i+j > 4) # etc. If you find lambdas confusing and prefer named functions, those will work just as well. def i_plus_j_gt_4(i, j): return i + j > 4 test1([0,1,2,3],[1,2,3,4], i_plus_j_gt_4) -- https://mail.python.org/mailman/listinfo/python-list