YAI: syntax for preset locals without using dummy args with defaults

Bengt Richter bokr at oz.net
Fri Jan 10 10:22:06 EST 2003


Yet another idea ;-)

Right now we often see

    def foo(x, y=default, z=some_expression):
        ...

where the purpose is not to have three parameters, but two
plus a local binding (z) in foo to the value of some_expression
evaluated in the def-time environment. z may bind something not
accessible later at call time, or it may be just to avoid recalculating
an expensive expression at each function call.

The subject line idea amounts to using the same parameter list mechanisms,
but not incrementing argcount (ok, a little more complex, but that's the
essence) Thus:


    def foo(x, y=default)(z=some_expression):
        ...

would make a function as if just from foo(x, y=default)
and the optional second "parameter list" would
make local bindings just like default arguments, but would
not make them part of the calling signature.

For longer lists of initializations, it is helpful that parens allow
putting things on multiple lines, but perhaps tempting to forget that
it's not a code block as I really wanted[1] ;-)

    def foo(x, y=default)(
        z = something                # preset local z
        pi = __import__('math').pi   # preset local pi
    ):
        if x<0 or y<0 or z<0: raise ValueError, 'Only call-time checks possible'
        return pi*(x*x-y*y)


----------------------------------------------------------------------------------
[1] Something like

    def foo(x, y=default):
        presets:
            z = something
            pi = __import__('math').pi
            twopi = 2.0*pi # not possible in parameter list version
            if z < 0: raise ValueError, 'Def-time preset check, possible with presets: block'
        if x<0 or y<0: raise ValueError, 'Call-time parameter check'
        return pi*(x*x-y*y)

I thought the first version above might be easier to implement, but
either way, having a sanctioned way to accomplish safe presetting of
function locals should make for a performance boost in many cases.

I think either version will be interesting for method definitions too.

Regards,
Bengt Richter




More information about the Python-list mailing list