W3docs

How do I check if a variable exists?

In Python, you can check if a variable exists by using the globals() or locals() function to check if the variable is in the global or local namespace, respectively.

In Python, you can check if a variable exists by using the globals() or locals() function to check if the variable is in the global or local namespace, respectively. For example:

Check if a variable exists in the global namespace in Python

python— editable, runs on the server

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Alternatively, you can use the globals().get() or locals().get() method to retrieve a variable's value. To safely check for existence first, use the in operator:

Check if a variable exists in the global namespace in Python by the get method

python— editable, runs on the server

It's also possible to use the vars() function to check if a variable exists in the current namespace, which is either the global or local namespace depending on where the function is called.

Check if a variable exists in the current namespace in Python

python— editable, runs on the server

Another way to check if a variable exists is to use the try-except block.

Check if a variable exists in Python in a try-except block

python— editable, runs on the server

Python favors the EAFP (Easier to Ask for Forgiveness than Permission) style, so using a try-except block is generally preferred over explicit existence checks.

You can also use the hasattr() method to check if an object has a certain attribute.

Check if an object has a certain attribute in Python

python— editable, runs on the server

Note that hasattr() checks for object attributes, not variables in the local or global namespace.