I've read various posts that polymorphism should be used instead of isinstance
, and I agree that makes sense when the use of isinstance
is checking the subtypes of a class to determine what to do. However, is the use of isinstance
acceptable when checking the type of an object in order to do something unrelated to the object itself?
For exammple:
last_little_err = last_big_err = None
for thing in things:
try:
thing.dothing()
except (LittleError, BigError) as err:
logger.error(err, extra={'thingObj': thing.name})
if isinstance(err, LittleError):
last_little_err = err
else:
last_big_err = err
else:
thing.success = True
if last_big_err is not None:
raise SuperBigError('A big thing error occurred') from last_big_err
elif last_little_err is not None:
display_error_warning(last_little_err)
I believe using isinstance
here is fine since I am not defining what the objects should do based on their type but rather checking their type to determine which variable should store it for later use. Is my reasoning valid?
things[0].dothing()
fails, your loop will keep going and keep trying todothing()
on the rest of the things. Is this international? – Alexander Mar 8 at 21:14raise
). – madeslurpy Mar 8 at 21:18