While I was hanging out in Python chat chat, someone came in and reported the following exception:
NameError: free variable 'var' referenced before assignment in enclosing scope
I had never seen this error message before, and the user provided only a small piece of code that could not have caused the error on its own, so I went looking for information, and ... there doesn’t seem to be much. While I was searching, the user reported his problem, which was resolved as a “space problem”, and then left the room.
After playing a little, I was able to reproduce the exception with the toy code as follows:
def multiplier(n): def multiply(x): return x * n del n return multiply
What gives me:
>>> triple = multiplier(3) >>> triple(5) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in multiply NameError: free variable 'n' referenced before assignment in enclosing scope
Everything is good and good, but it’s hard for me to figure out how this exception can occur in the wild, given that my example is higher
- Pretty stupid
- It is unlikely to happen by accident.
... but obviously this is so, given the report I mentioned at the beginning of this question.
So - how does this particular exception occur in real code?
source share