[Python-ideas] Default arguments in Python - the return - running out of ideas but...

CTO debatem1 at gmail.com
Thu May 14 01:03:34 CEST 2009


On May 13, 3:44 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> On 13 May 2009, at 20:18, CTO wrote:
>
> > Why not just push for some decorators that do this to be included in
> > stdlib? I see the utility, but not the point of adding extra syntax.
>
> >>>> @Runtime
> > ... def f(x=a**2+2b+c):
> > ...    return x
> > ...
> >>>> a = 1
> >>>> b = 2
> >>>> c = 3
> >>>> f()
> > 8
>
> > This seems much more intuitive and useful to me than adding new
> > meanings to yield.
>
> This is not possible.
>
>      def f(x=a**2+2*b+c):
>         return x
>
> is compiled to something very much like:
>
>      _tmp = x**2+2*b+c
>      def f(x=_tmp):
>         return x
>
> So it is impossible to find out what expression yields the default  
> value of x by just looking at f.  You have to use lambda or use George  
> Sakkis' idea of using strings for defaults and evaluating them at call-
> time (but I'm not sure this will work reliably with nested functions).
>
> --
> Arnaud

Thanks for the input, but I've already written the code to do this.
It
is available at <URL:http://code.activestate.com/recipes/576751/>.
For
those with hyperlink allergies, the snippet posted above reevaluates
the function whenever it is called, and can be used like so:

>>> from runtime import runtime
>>> @runtime
... def example1(x, y=[]):
...    y.append(x)
...    return y
...
>>> example1(1)
[1]
>>> example1(2)
[2]

or, as posted above,

>>> a, b, c = 0, 1, 2
>>> @runtime
... def example2(x=a**2+2*b+c):
...     return x
...
>>> example2()
4
>>> a = 5
>>> example2()
29

The gode given is slow and ugly, but it does appear-
at least to me- to do what is being asked here.

Geremy Condra



More information about the Python-ideas mailing list