51

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"
import this
  • 517
  • 2
  • 7
  • 21
grigoryvp
  • 40,413
  • 64
  • 174
  • 277
  • third-party class, need to set a flag for my private purpose, don't want to mess class __init__() – grigoryvp Apr 15 '09 at 16:19
  • 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 Apr 15 '09 at 17:26
  • 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 Apr 15 '09 at 23:13
  • 2
    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 Jul 19 '13 at 06:46
  • @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 Aug 13 '13 at 22:47

5 Answers5

29

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
  • 31,360
  • 7
  • 64
  • 74
  • 1
    I think he's just looking for hasattr(). – monkut Apr 15 '09 at 04:44
  • 3
    Yeah, most probably. And what about a global variable? (declared in module, not in a class namespace)? – grigoryvp Apr 15 '09 at 16:20
  • 1
    @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 Apr 15 '09 at 18:55
  • 1
    **Don't miss this answer:** https://stackoverflow.com/a/843293/1447509 – cssyphus Aug 19 '18 at 16:32
  • for local variables not attached to an object: `print('defined') if 'myVar' in locals() else print('undefined')`. This is more generic than using `globals()`, because `locals()` includes all names defined in `globals()`. – kelloti Dec 13 '19 at 17:00
25
try:
    print myObject.myVar
except NameError:
    print "not defined"
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
hbw
  • 15,560
  • 6
  • 51
  • 58
11

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"
physicsmichael
  • 4,793
  • 11
  • 35
  • 54
10

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.

Jonas G. Drange
  • 8,749
  • 2
  • 27
  • 38
sina651
  • 109
  • 1
  • 2
3

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