On 3/25/2015 1:29 PM, 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")

The standard solution to the above is to have a boolean parameter, such as print_wanted=False.

test1([0,1,2,3],[1,2,3,4],"i+j >4")
print("Bar")

For this, follow Ian's suggestion of passing a predicate function.

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to