Reputation: 329
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?
Upvotes: 2
Views: 187
Reputation: 601679
The del
statement implicitly renders the name someClass
local for the whole function, so the line
someInstance = someClass()
tries to look up a local name someClass
, which is not defined at that point. The del
statement 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
:
def someFunction():
global someClass
...
del someClass
Upvotes: 8