How do I check if a variable exists? How do I check if a variable exists? python python

How do I check if a variable exists?


To check the existence of a local variable:

if 'myVar' in locals():  # myVar exists.

To check the existence of a global variable:

if 'myVar' in globals():  # myVar exists.

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):  # obj.attr_name exists.


The use of variables that have yet to been defined or set (implicitly or explicitly) is often a bad thing in any language, since it tends to indicate that the logic of the program hasn't been thought through properly, and is likely to result in unpredictable behaviour.

If you need to do it in Python, the following trick, which is similar to yours, will ensure that a variable has some value before use:

try:    myVarexcept NameError:    myVar = None      # or some other default value.# Now you're free to use myVar without Python complaining.

However, I'm still not convinced that's a good idea - in my opinion, you should try to refactor your code so that this situation does not occur.

By way of an example, the following code was given below in a comment, to allow line drawing from a previous point to the current point:

if last:    draw(last, current);last = current

In the case where last has not been bound to a value, that won't help in Python at all since even the checking of last will raise an exception. A better idea would be to ensure last does have a value, one that can be used to decide whether or not it is valid. That would be something like:

last = None# some time passes ...if last is not None:    draw(last, current);last = current

That ensures the variable exists and that you only use it if it's valid for what you need it for. This is what I assume the if last was meant to do in the comment code (but didn't), and you can still add the code to force this if you have no control over the initial setting of the variable, using the exception method above:

# Variable 'last' may or may not be bound to a value at this point.try:    lastexcept NameError:    last = None# It will always now be bound to a value at this point.if last is not None:    draw(last, current);last = current


A simple way is to initialize it at first saying myVar = None

Then later on:

if myVar is not None:    # Do something


matomo