Supply condition in function call

Manuel Graune manuel.graune at koeln.de
Fri Mar 27 15:46:22 EDT 2015


Peter Otten <__peter__ at web.de> writes:

> Cameron Simpson wrote:
>
>>   test1([0,1,2,3], [1,2,3,4], condition_test)
>> 
>> This passes the local variables inside test1() to "condition" as a single
>> parameter. Now, I grant that vars['i'] is a miracle of tediousness. So
>> consider this elaboration:
>> 
>>   from collections import namedtuple
>> 
>>   condition_test = lambda vars: vars.i + vars.j > 4
>> 
>>   def test1(a, b, condition):
>>     for i, j in zip(a,b):
>>       c = i + j
>>       vars = locals()
>>       varnames = list(vars.keys())
>
> instead or pass the list of arguments explicitly, optionally with some 
> inspect fallback:
>
> $ cat pass_condition_inspect.py
> import inspect
>
> def test3(a, b, condition, args=None):
>     if args is None:
>         args = inspect.getargspec(condition).args
>
>     for i, j in zip(a,b):
>         c = i + j
>         _locals = locals()
>         if condition(*[_locals[name] for name in args]):
>             print("Foo", i, j)
>
> def condition(c, i):
>     return i * i > c
>
> test3([1, 2, 3], [2, 3, 4], condition)
> print("---")
> # note reverse order of argument names
> test3([1, 2, 3], [2, 3, 4], condition, ["i", "c"]) 
> $ python3 pass_condition_inspect.py
> Foo 3 4
> ---
> Foo 1 2
> Foo 2 3
> Foo 3 4
>

I'm just comparing the different solutions. For most of them, the
logic and the costs/benefits are pretty clear to me. Can you
elaborate on your code? I'm not clear what you are achieving with
explicitly passing the arguments instead of simply passing some
variant of the complete locals()-dictionary.


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