4 ms·
I think `nonlocal` is a prime example of a leaky abstraction. Can anyone explain the advantages of using references for normally primitive variables?
by tkahn6 16y ago
I think `nonlocal` is a prime example of a leaky abstraction. Can anyone explain the advantages of using references for normally primitive variables?
- artsrc 16y agononlocal 'leaks' that assigning an new identifier declares a new local variable. This is part of the abstraction not a leak. I don't think I understand your other question.
- parfe 16y agoWhat is your definition of primitive?
- kgo 16y agoThere are no primitive variables in python. Even ints, strings, floats, etc point to a reference of an object. All nonlocal does is point the variables reference to a different object. As to the advantages... Well for one you can use the variables in closures...
- andolanra 16y agoI'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.)