[Python-ideas] Default arguments in Python - the return

Georg Brandl g.brandl at gmx.net
Sun May 10 16:58:30 CEST 2009


spir schrieb:

> Also, func attributes are an alternative for another common (mis)use of default arguments, namely the case of a function factory:
> 
> def paramPower(exponent):
>    ### instead of "def power(number, exponent=exponent)"
>    ### just set exponent on the func:
>    def power(number):
>       return number**power.exponent
>    power.exponent = exponent
>    return power
> power3 = paramPower(3) ; power5 = paramPower(5)
> print power3(2) ; print power5(2)
> ==>
> 8
> 32

You don't need a function attribute here; just "exponent" will work fine.

The problem is where you define multiple functions, e.g. in a "for" loop,
and function attributes don't help there:

   adders = []

   for i in range(10):
       def adder(x):
           return x + i

This will fail to do what it seems to do; you need to have some kind of
binding "i" in a scope where it stays constant.  You could use a "make_adder"
factory function, similar to your paramPower, but that is more kludgy than
necessary, because it can easily be solved by a default argument.

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list