Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

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?

1 Answer

0 votes
by (10.9k points)
edited by

@Selena, The 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 this helps!

Related questions

0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer

31k questions

32.4k answers

501 comments

693 users

Browse Categories

...