1

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.

Lewis
  • 1,310
  • 1
  • 15
  • 28
  • possible duplicate of [Does Python support short-circuiting?](http://stackoverflow.com/questions/2580136/does-python-support-short-circuiting) – abyx Feb 27 '11 at 08:51
  • Pretty much, yup! Didn't know the term used for this (short-circuting). Feel free to delete/close if needed. – Lewis Feb 27 '11 at 08:56

1 Answers1

5

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"
senderle
  • 145,869
  • 36
  • 209
  • 233
  • Exactly what I wanted to know, and really useful information about isinstance(). Thanks! – Lewis Feb 27 '11 at 08:57