So let's say you've got an application with a variable that you will be creating an instance of when you load it independently (ie when you use if __name__ == '__main__'
).
Also, there is a method that is to be called for when a client imports the application for use within another application. This method will also instantiate this variable.
What I want to do is test whether the variable has already been instantiated before defining it (so I don't have to go through the creation of the object twice). My intuition told me to use if SOME_VARIABLE is not None: #instantiate here
but this yields the error
local variable 'SOME_VARIABLE' referenced before assignment
What gives?
It's an error to access a variable before it is initialized. An uninitialized variable's value isn't None; accessing it just raises an exception.
You can catch the exception if you like:
>>> try:
... foo = x
... except NameError:
... x = 5
... foo = 1
In a class, you can provide a default value of None and check for that to see if it has changed on a particular instance (assuming that None isn't a valid value for that particular variable):
class Foo(object):
bar = None
def foo(self):
if self.bar is None:
self.bar = 5
return self.bar
You can try if 'varname' in locals()
(you probably also have to check globals()
, and maybe some other places), or just read from the variable and catch the NameError
exception which will be thrown when it doesn't exist.
But if you just want the else-case of if __name__ == '__main__'
, why not just do:
if __name__ == '__main__'
myvar = 'as_main'
else:
myvar = 'as_import'
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