Supply condition in function call

Manuel Graune manuel.graune at koeln.de
Thu Mar 26 02:27:39 EDT 2015


Gary Herron <gherron at digipen.edu> writes:

> On 03/25/2015 10:29 AM, Manuel Graune wrote:
>>
>> 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")
>>
>
> 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):

This seems to be the right direction and a good solution for simple
cases. Unfortunately this:

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

is not as concise as I had hoped for. Is there a possibility to do
(maybe with a helper function inside the main function's body) solve
this more elegantly? I'm thinking of some combination of e. g. **kwargs,
dir() and introspection.

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