a = b = 1 just syntactic sugar?

Ed Avis ed at membled.com
Sat Jun 14 09:25:52 EDT 2003


"Terry Reedy" <tjreedy at udel.edu> writes:

>You can read but not rebind variable in outer scope.  But this works:
>
>def make_counter():
>  counter = [0]
>  def incr():
>    counter[0] += 1
>    return counter[0]
>  return incr
>>>> c1=make_counter()
>>>> c2=make_counter()
>>>> print c1(), c1(), c2(), c2()
>1 2 1 2

Yes.  A similar technique can be used to simulate closures in other
languages, for example in C++

    #include <iostream>
    struct incr {
        int* c;
        incr(int *c) :c(c) {}
	int operator() { return ++c; }
    };
    typedef int *fi();
    fi make_counter()
    {
        int* counter = new int;
        return incr(counter);
    }
    int main()
    {
        c1 = make_counter();
        c2 = make_counter();
        std::cout << c1() << c1() << c2() << c2() << std::endl;
        return 0;
    }
    
(Sorry, my compiler is playing up so I have not tested the above
code.)

The point is that you have to wrap the integer explicitly in some kind
of container, you can't just 'capture' a variable without doing
anything extra and proeed to play about with its value from other
scopes.  A local variable is strictly local to the block that contains
it (in C++, it will be destroyed on exit from the block) and you can't
make it break free and swim about attached to some closure just by
returning a function that uses it.

-- 
Ed Avis <ed at membled.com>




More information about the Python-list mailing list