I’m a self-taught programmer with no formal training, so please forgive me in advance if this is a stupid question.
While programming in Python I found something weird:
from someModule import someClass
def someFunction():
someInstance = someClass()
print "foo"
del someClass
someFunction()
This immediately dies with an unbound local variable error:
UnboundLocalError: local variable 'someClass' referenced before assignment
Commenting out the delete statement fixes the problem:
...
#del someClass
...
and it returns:
foo
So, 2 questions:
1) the del statement is at the end of the function. Why is it being called before the bits at the beginning?
2) Why is it giving me an “unbound local variable” error? Shouldn’t it be an “unbound global variable” error?
The
delstatement implicitly renders the namesomeClasslocal for the whole function, so the linetries to look up a local name
someClass, which is not defined at that point. Thedelstatement isn’t executed early — the name isn’t defined right from the beginning.If you really want to do something like this (hint: you don’t), you must declare the name
global: