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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With