On 04/06/10 18:42, Alain Ketterlin wrote: > Alain Ketterlin <al...@dpt-info.u-strasbg.fr> writes: > >> d = dict() >> for r in [1,2,3]: >> d[r] = [r for r in [4,5,6]] >> print d > > Thanks to Chris and Paul for the details (the list comp. r actually > leaks). I should have found this by myself. > > My background is more on functional programming languages, that's why I > thought the list comprehension iterator should be purely local. And yes, > I think a "classical" for-loop iterator should also be local to the > loop, but I understand this may be too counter-intuitive to many :-)
Actually in other programming languages, loop counter is usually local: for (int i = 0; i < something; i++) { .... } foo(i); // illegal The reason why python's loop counter leaks is for implementation simplicity because otherwise python will have to deal with multi-layered local namespace. Currently in python, the local namespace is just sugar for an array access (a bit of hand-waving here). In other languages, a {} block is a namespace and nested {} block means nested namespace even if they're still in a single function; in python there is only a flat local namespace and the names resolver becomes a thousand times simpler (and faster). -- http://mail.python.org/mailman/listinfo/python-list