On May 13, 3:44 pm, Arnaud Delobelle arno...@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.
... def f(x=a**2+2b+c): ... return x ...
a = 1 b = 2 c = 3 f()
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).
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 ...
or, as posted above,
a, b, c = 0, 1, 2 @runtime
... def example2(x=a**2+2*b+c): ... return x ...
a = 5 example2()
The gode given is slow and ugly, but it does appear- at least to me- to do what is being asked here.