Code blocks as parameters

James_Althoff at i2.com James_Althoff at i2.com
Wed May 2 00:33:12 CEST 2001


Marcin writes
>Tue, 1 May 2001 12:51:02 -0700, James_Althoff at i2.com
<James_Althoff at i2.com> pisze:
>
>> func(arg1,arg2) targ1,targ2:
>>     statements using targ1 and/or targ2
>>
>> which would turn into:
>>
>> def thunk(targ1,targ2):
>>     statements using targ1 and/or targ2
>
>What if func returns a meaningful return value which I want to use?

This should be fine since any function can return a value.

result = function(thunk,arg1,arg2)

should be no different than

function(thunk,arg1,arg2)

except that, of course, it assigns its return value to "result".
(This assumes that "function" returns a value of interest in this example.)

If we _could_ write:

result = function():
    statements

as an alternative spelling for:

def thunk():
    statements
result = function(thunk)

there would be, I guess, the issue that the ":" makes "function():" _look_
more like a statement and statements don't return values and don't
participate in expressions.  But we _would_ want "function():" to return a
value and participate in expressions in the same way that "function(thunk)"
does.  So perhaps ":" is not the best syntactic marker for this purpose
(although I _do_ like it, myself).


>Can this construct be used inside a subexpression?

Don't know, but that would certainly be preferred.  :-)

I would clearly like to be able to write:

window.showWaitCursorDuring():
    window.showStatusDuring(message='Searching...'):
        form.prepare()
        form.executeQuery()
    window.showStatusDuring(message='Displaying...'):
        form.displayResults()

So,

result1 = func1():
    statements1
    result2 = func2():
        statements2
        return value2
    return value1

would become:

def thunk1():
    statements1
    def thunk2():
        statements2
        return value2
    result2 = func2(thunk2)
    return value1
result1 = func1(thunk1)

I guess it would have to be understood that the scoping rules are those
that apply to functions (presumably the new nested scope rules) since all
of this ultimately turns into functions (and nested functions).  Since said
scoping rules don't match the scoping rules for "actual" statements (like
if xxx:, try:, for xxx:, etc.) it might (again) be better to use a
syntactic marker other than ":".

>
>I'm afraid that the syntax has problems in a general cas3

I wouldn't be surprised.  The distinction between statements and
expressions in Python along with its indentation-based syntax makes all of
this a challenge.

>, so I would
>like to have at least
>    v = func(arg1, arg2) targ1, targ2:
>        statements
>and
>    return func(arg1, arg2) targ1, targ2:
>        statements
>
>--
> __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/





More information about the Python-list mailing list