Generator issue: exceptions while initializing arguments

Jason Orendorff jason.orendorff at gmail.com
Mon Sep 10 16:28:57 PDT 2012


(re-adding the list)

On Mon, Sep 10, 2012 at 5:20 PM, Tobie Langel <tobie.langel at gmail.com> wrote:
> Yes, sorry for being unclear. What I meant to say was that I would
> expect EXPR1 and EXPR2 to have been evaluated within the lexical scope
> of f() at the time of function declaration, in source order, so:

That is how it works in Python, and it's astonishing when the
default-expression produces something mutable:

    def getNames(target=[]):
        target.append('kaitlin')
        return target

    getNames()    # returns ['kaitlin']
    getNames()    # returns the same list, which now contains
['kaitlin', 'kaitlin']

It also means that later arguments' default-expressions can't use
earlier arguments' values, because at the time the default-expression
is evaluated, those arguments don't have values yet.

C++ evaluates the default-expression each time the value is needed.
This seems more sensible to me and it's what has been specified (and
implemented in SM) for ES6.

> var FOO = 2;
>
> function f(y = FOO + 3) {
>   return y;
> }
>
> f();
>>>> 5
> FOO = 45;
>>>> 45
> f();
>>>> 5

This example doesn't bring up any scoping issues, though.  It only
brings up timing issues.  I think those are pretty well settled.

-j


More information about the es-discuss mailing list