How do I check if a variable exists?

320    Asked by AnushaAcharya in Python , Asked on Apr 7, 2021

 I want to check if a variable exists. Now I'm doing something like this:

try:

   yourVar

except NameError:

   # Do something.

Are there other ways without exceptions?

Answered by Anusha Acharya

To solve python check if a variable exists you should follow the below-method varies with the type of variable.

1. If you want to check the existence of a local variable use:

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

2.if you want to check the existence of a global variable use:

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

3.If you want to check if an object has an attribute:

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

Hope my answer helps!



Your Answer

Interviews

Parent Categories