Reputation: 1350
Say I have a myObject class with a member called prop. I have a variable var which may or may not be a myObject. I want to check if prop holds a certain value, and if so, do something, and if it doesn't, or var is not a myObject, do nothng.
Would it be safe to do the following:
if isinstance(var, myObject) and var.prop == 10:
#Do something
Basically, is it guaranteed that the second part of that if statement will not be checked if the first part evaluates to False? If it is checked even if var is not a myObject, an error will be thrown.
Upvotes: 1
Views: 114
Reputation: 150987
To answer your question, yes, and
short circuits. But I wouldn't do it that way. A better method is to use hasattr
or a try, except
block.
if hasattr(var, 'prop') and var.prop == 10:
print var.prop
Or (if it's unusual for a propless var to come along):
try:
print var.prop
except AttributeError:
print "propless var"
Upvotes: 5