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

Bengt Richter bokr at oz.net
Sat Jan 11 00:11:02 CET 2003


On Fri, 10 Jan 2003 10:36:54 -0700, Andrew Dalke <adalke at mindspring.com> wrote:

>Bengt Richter wrote:
>>     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.
>
>I offer the following to be able to compare this proposal with
>what I've done to solve this problem
>
>
>def _foo(x, y, z = some_expresssion):
>   ....
>
>def foo(x, y = default):
>   _foo(x, y)

That strikes me as a lot of function call overhead,
compared to the foo you get with

def foomaker(yd= default, z = some_expression):
    def foo(x, y=yd):
        return x*y*z # or other use
    return foo

foo = foomaker()

IOW, I wasn't saying there isn't an effective way, just that there's no
concise spelling like, e.g.,

    def foo(x, y=default)(z=some_expression):
        return x*y*z # or other use
  
where that means z gets a local binding like y,
but is not part of the parameter list.

>
>However, I do this only rarely (mostly for recursive functions)
>since it doesn't gain all that much over
>
>_default_z = some_expression
>
>def foo(x, y = default):
>   z = _default_z
>   ...
Indeed, a plain global reference should be considerably faster
than a double function call as in your foo's call of (global!) _foo ;-)

Maybe you mis-copied something you'd done before?

Regards,
Bengt Richter




More information about the Python-list mailing list