Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to check that a variable is defined in python? [duplicate]

Tags:

python

Is there any way to check if a variable (class member or standalone) with specified name is defined? Example:

if "myVar" in myObject.__dict__ : # not an easy way   print myObject.myVar else   print "not defined" 
like image 592
grigoryvp Avatar asked Apr 15 '09 04:04

grigoryvp


People also ask

How do you test if a variable is defined in Python?

To check if the variable is defined in a local scope, you can use the locals() function, which returns a dictionary representing the current local symbol table. if 'x' in locals(): print('Variable exist. ')

How do you check the type of a variable in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do I check if a variable is global in Python?

To check if a global variable exists in Python, use the in operator against the output of globals() function, which has a dictionary of a current global variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise False.


1 Answers

A compact way:

print myObject.myVar if hasattr(myObject, 'myVar') else 'not defined' 

htw's way is more Pythonic, though.

hasattr() is different from x in y.__dict__, though: hasattr() takes inherited class attributes into account, as well as dynamic ones returned from __getattr__, whereas y.__dict__ only contains those objects that are attributes of the y instance.

like image 156
Miles Avatar answered Oct 14 '22 02:10

Miles