Supply condition in function call

Manuel Graune manuel.graune at koeln.de
Wed Mar 25 13:51:21 EDT 2015


Joel Goldstick <joel.goldstick at gmail.com> writes:

> On Wed, Mar 25, 2015 at 1:29 PM, Manuel Graune <manuel.graune at koeln.de> wrote:
>>
>> def test1(a, b, condition="True"):
>>     for i,j in zip(a,b):
>>         c=i+j
>>         if eval(condition):
>>            print("Foo")
>>
> I'm not sure I understand your question, but condition will evaluate
> to True or False regardless, so:
>          if condition:
>             print ("Foo")
>          else:
>             print ("Bar")
>

The point is (see examples below) to specify the condition that is to be
evaluated when calling the function (as opposed to when stating the function). 

> eval can be dangerous as someone could put some unknown command with
> side effects in condition
>

I know that. That's why I'm looking for an alternative. ;-)

>> 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")
>>
>> Resulting in
>>
>> Foo
>> Foo
>> Bar
>> Foo
>> Foo
>> Bar
>> Foo

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



More information about the Python-list mailing list