Categories
Python Answers

How to check if a variable exists with Python?

Spread the love

Sometimes, we want to check if a variable exists with Python.

In this article, we’ll look at how to check if a variable exists with Python.

How to check if a variable exists with Python?

To check if a variable exists with Python, we can check with various functions.

For instance, we write

if 'my_var' in locals():
  # ...

to call locals to return a dict with all the local variables.

We use 'my_var' in locals() to check if my_var is a local variable in the current scope.

Likewise, we call globals to return a dict with a list of global variables.

For instance, we write

if 'my_var' in glocals():
  # ...

to check if the my_var variable is a global variable in the current module.

To check if an attribute is in an object, we use hasattr.

For instance, we write

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

to call hasattr to check if the attr_name attribute is in the obj object.

Conclusion

To check if a variable exists with Python, we can check with various functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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