cosmologicon / pywat

Python wats
1.22k stars 99 forks source link

Scope #30

Open coleifer opened 8 years ago

coleifer commented 8 years ago

Here's one that blew my mind (and my co-workers):

def incrementer():
    i = 0
    def increment():
        i = i + 1
        return i
    return increment

Looks OK. Let's try it.

>>> i = incrementer()
>>> i()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-3-fa1b63ea38ec> in <module>()
----> 1 i()

<ipython-input-1-482b5332e967> in increment()
      2         i = 0
      3         def increment():
----> 4                 i = i + 1
      5                 return i
      6         return increment

UnboundLocalError: local variable 'i' referenced before assignment

Fuck, even JavaScript got this one right!