Supply condition in function call
Cameron Simpson
cs at zip.com.au
Fri Mar 27 18:55:57 EDT 2015
On 27Mar2015 21:02, Manuel Graune <manuel.graune at koeln.de> wrote:
>Cameron Simpson <cs at zip.com.au> writes:
>
>> 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())
>> varstupletype = namedtuple("locals", varnames)
>> varstuple = varstupletype(*[ vars[k] for k in varnames ])
>> if condition(varstuple):
>> print("Foo")
>>
>> Here, the condition_test function/lambda uses "vars.i" and "vars.j",
>> which i think you'll agree is easier to read and write. The price is
>> the construction of a "namedtuple" to hold the variable name
>> values. See:
>>
>> https://docs.python.org/3/library/collections.html#collections.namedtuple
>>
>
>This is probably getting off topic,
I think it is on topic.
>but is there any relevant difference
>or benefit to using namedtuple instead of something like types.SimpleNamespace?
>
>https://docs.python.org/3/library/types.html#additional-utility-classes-and-functions
Probably not. SimpleNamespace is much easier to construct; I hadn't thought of
it. As the doc remarks, a namedtuple is probably better for fixed records (eg
mapping out rows of a CSV file) because it will prevent you using the wrong
name. But for a comparison function SimpleNamespace is probably better.
Cheers,
Cameron Simpson <cs at zip.com.au>
The Horn of Vengeance: When he pushes the horn button, the device produces
the sound of fingernails scraping on a blackboard, amplified beyond pain
threshold. If that doesn't work, the horn then plays the Pina Colada song.
More information about the Python-list
mailing list