tags:

views:

2659

answers:

3

Hello.

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

if "myVar" in myObject.__dict__ : # not an easy way
  print myObject.myVar
else
  print "not defined"
+6  A: 
try:
    print myObject.myVar
except NameError:
    print "not defined"
htw
At least get the variables and output right :-) +1
paxdiablo
Oops, nice catch. Thanks for the edit.
htw
If myObject is defined, but doesn't have a 'myVar', you'll get an AttributeError instead.
James Bennett
+1  A: 

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"
vgm64
+6  A: 

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.

Miles
I think he's just looking for hasattr().
monkut
Yeah, most probably. And what about a global variable? (declared in module, not in a class namespace)?
Eye of Hell
@Eye of Hell: perhaps (x in globals()), but my real answer would be that code that needs to do that is un-Pythonic and should really be initializing the variable to None.
Miles