Supply condition in function call

Grant Edwards invalid at invalid.invalid
Thu Mar 26 11:41:22 EDT 2015


On 2015-03-25, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Wed, Mar 25, 2015 at 1:53 PM, Grant Edwards <invalid at invalid.invalid> wrote:
>> On 2015-03-25, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>>> On Wed, Mar 25, 2015 at 11:29 AM, Manuel Graune <manuel.graune at koeln.de> wrote:
>>>
>>>> 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 [...]
>>>
>>> Pass the condition as a function.
>>>
>>> def test1(a, b, condition=lambda i, j: True):
>>>     for i,j in zip(a,b):
>>>         c=i+j
>>>         if condition(i, j):
>>>             print("Foo")
>>>
>>> test1([0,1,2,3],[1,2,3,4], lambda i, j: i+j > 4)
>>> # etc.
>>
>> FWIW, back in the day such a function was referred to as a "thunk"
>> (particularly if it was auto-generated by a compiler that used
>> pass-by-name instead of pass-by-value or pass-by-reference):
>>
>>   http://en.wikipedia.org/wiki/Thunk
>>
>> Dunno if people still use that term or not.
>
> I've heard the term (though not since my college days, I think), but
> I've always understood thunks to be parameterless (hence the use as a
> form of pass-by-name).

You're right -- I misread the example. Somehow I skipped the "for i,j"
line completely, and was thinking that i and j were defined in the
caller's context. Thus the OP was trying to implment something akin to
call by name.

-- 
Grant Edwards               grant.b.edwards        Yow! Here I am in the
                                  at               POSTERIOR OLFACTORY LOBULE
                              gmail.com            but I don't see CARL SAGAN
                                                   anywhere!!



More information about the Python-list mailing list