43
votes

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"
5
third-party class, need to set a flag for my private purpose, don't want to mess class __init__() - grigoryvp
That's really confusing. Why write a lot of code to determine what variables are used? Just create an instance, print instance.__dict__.keys() or do dir(instance) and you know all the attribute names. - S.Lott
I'm afraid I'm also confused. The question asks about both class members and standalone vars. Obviously, there's no init for standalone, top-level vars; what 3rd party miasma is so poorly built that so many of its variables, at multiple scope levels, are at risk of being completely non-existent? - Jarret Hardie
Here's an example that led me to this question. In a Django app we have a settings module, with optional settings like "# MYLIST =[1,2]". I want to extend the list if it exists (MYLIST += [3]), or define it if it dooesn't. (MYLIST = [3]). - Steve Bennett
@S.Lott I'm also here because of a settings file. If a variable is set in the settings file, I want to use it. If it's not, I want to do something else. Initializing all the possible settings variables to none seems impractical. - ForeverWintr

5 Answers

29
votes

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.

25
votes
try:
    print myObject.myVar
except NameError:
    print "not defined"
11
votes

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"
5
votes

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.

3
votes

Read and or tricks in python : 'a' in locals() and a