[Edu-sig] of Brython, JavaScript and closures

kirby urner kirby.urner at gmail.com
Fri Apr 15 15:21:56 EDT 2016


On Fri, Apr 15, 2016 at 10:40 AM, kirby urner <kirby.urner at gmail.com> wrote:



>
> The increm function was originally looking in the global namespace for x...
>


That's not quite right either as this is simply wrong as a complete module:

x = 0

def createIncrementor(x):
        def increm():
                x = x + 1
                return x
        return increm

The "referenced before assignment" error will occur regardless of the
presence of a global x.

The choices to make increm work would be:

x = 100

def createIncrementor(x):
        def increm():
                global x
                x = x + 1
                return x
        return increm

(a module is a kind of closure / enclosure -- coming in ES6 right?)

or:

def createIncrementor(x):
        def increm():
                nonlocal x
                x = x + 1
                return x
        return increm

for an even more enclosed closure.

One may even remove x = from the module's global namespace and inject it
retroactively:

>>> from closure import createIncrementor
>>> inc = createIncrementor(5)
>>> inc()
Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
    inc()
  File "/Users/kurner/Documents/classroom_labs/closure.py", line 4, in
increm
    x = x + 1
NameError: global name 'x' is not defined
>>> x = 100  # this won't work either as '__main__' is not where it looks
>>> inc()
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    inc()
  File "/Users/kurner/Documents/classroom_labs/closure.py", line 4, in
increm
    x = x + 1
NameError: global name 'x' is not defined
>>> closure.x = 100   # this would work if I added closure to the namespace
Traceback (most recent call last):
  File "<pyshell#83>", line 1, in <module>
    closure.x = 100
NameError: name 'closure' is not defined
>>> import closure     # which I do here
>>> closure.x = 100
>>> inc()                    # and now the earlier imported function works
with no problems
101


Kirby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20160415/d1fea56c/attachment.html>


More information about the Edu-sig mailing list