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:
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):