I'm currently using a try/except block to treat a particular variable as an iterable when I can, but handle it a different, though correct, manner when it isn't iterable.
My problem is that a TypeException may be thrown for reasons other than trying to iterate with a non-iterable. My check was to use the message attached to the TypeException to ensure that this was the reason and not something like an unsupported operand.
But messages as a part of exceptions have been deprecated. So, how can I check on the reason for my TypeException?
For the sake of completeness, the code I'm using is fairly similar to this:
try:
deref = [orig[x].value.flatten() for x in y]
except TypeError as ex:
if "object is not iterable" in ex.message:
x = y
deref = [orig[x].value.flatten()]
else:
raise
Separate the part that throws the exception you're interested in from the parts that throw unrelated exceptions:
try:
iterator = iter(y)
except TypeError:
handle_that()
else:
do_whatever_with([orig[x].value.flatten() for x in iterator])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With