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

Question:

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"
Asked By: grigoryvp

||

Answers:

try:
    print myObject.myVar
except NameError:
    print "not defined"
Answered By: hbw

Paolo is right, there may be something off with the way you’re doing things if this is needed. But if you’re just doing something quick and dirty you probably don’t care about Idiomatic Python anway, then this may be shorter.

try: x
except: print "var doesn't exist"
Answered By: physicsmichael

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.

Answered By: Miles

Read and or tricks in python :
‘a’ in locals() and a

To test if the variable, myvar, is defined:

result = dir().count('myvar')

If myvar is defined, result is 1, otherwise it would be 0.

This works fine in Python version 3.1.2.

Answered By: sina651
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.