Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a variable exists?

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

try:    myVar except NameError:    # Do something. 

Are there other ways without exceptions?

like image 634
Max Frai Avatar asked May 09 '09 13:05

Max Frai


People also ask

How do I check if a variable exists in Python?

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.

How do you know if a variable is defined?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do I check if a variable exists in C++?

There is no way in the C++ language to check whether a variable is initialized or not (although class types with constructors will be initialized automatically). Instead, what you need to do is provide constructor(s) that initialize your class to a valid state.


1 Answers

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. 
like image 166
Ayman Hourieh Avatar answered Oct 03 '22 07:10

Ayman Hourieh