Rather than worrying about if a variable is declared, declare all variables from the start. You can give variables some value to indicate that it is still in a initial state, such as
foo = None
or, if you want to use None
for some other purpose, you can create a unique value to indicate the initial state, such as
INITIAL = object()
foo = INITIAL
Later, if you need to check if the variable has been set, you could just use if
:
if foo == INITIAL:
I think the main advantages to doing it this way are
- You'll never accidentally raise a NameError.
- There will be one place in your code where all the variables are introduced, so readers of your code do not have to wonder what variables are in play.
By the way, it is similarly a good idea to define all instance attributes in __init__
, so there is no question about what attributes an instance may have.