3 ms·
I'm not entirely sure what you mean by "using references for normally primitive variables." Nonlocal doesn't change whether variables are references or not, onl
by andolanra 16y ago
I'm not entirely sure what you mean by "using references for normally primitive variables." Nonlocal doesn't change whether variables are references or not, only the semantics of assignment. By default, all assignments take place in the local scope; if you've indicated that a variable is nonlocal, then instead of creating a new variable in that scope you assign instead to the variable of that name in the nearest enclosing scope. All variables in Python are references to objects, so there is no such thing as a "primitive" type, but that was true even before the nonlocal keyword was introduced, so it's not relevant here.
Lisp has had proper support for lexical scoping and closures for ages, and nobody has ever accused it of being a leaky abstraction there, either. The Scheme example of the same program would be
(define (make-counter)
(let ((n 0))
(lambda ()
(let ((temp n))
(set! n (+ n 1))
temp))))
All that's happening here is that let is creating a new variable, and set! is looking for the nearest enclosing scope--which turns out to be the let--and assigning to that one. (Okay, there are minor semantic differences, because let creates a new scope instead of creating a new variable in the local scope, but that's not really relevant to the discussion at hand.)