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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)