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])

Resulting in

Foo
Foo
Bar
Foo
Foo
Bar
Foo
Bar
Foo
Foo
Foo
Foo

Thanks for your help

Regards,

Manuel

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to