python – How do I check if a variable exists?

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 hasnt 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:
    myVar
except NameError:
    myVar = None      # or some other default value.

# Now youre free to use myVar without Python complaining.

However, Im still not convinced thats 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 wont 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 its valid for what you need it for. This is what I assume the if last was meant to do in the comment code (but didnt), 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:
    last
except 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

python – How do I check if a variable exists?

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

Then later on:

if myVar is not None:
    # Do something

Leave a Reply

Your email address will not be published. Required fields are marked *