Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the reason for a Python Type Error

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
like image 606
user1245262 Avatar asked Apr 28 '26 06:04

user1245262


1 Answers

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])
like image 153
user2357112 supports Monica Avatar answered Apr 29 '26 20:04

user2357112 supports Monica