Reputation: 1779
How might I store the value of an exception as a variable? Looking at older posts, such as the one below, these methods do not work in Python3. What should I do without using a pip install package?
My goal is to iterate through data, checking it all for various things, and retain all the errors to put into a spreadsheet.
Older post: Python: catch any exception and put it in a variable
MWE:
import sys
# one way to do this
test_val = 'stringing'
try:
assert isinstance(test_val, int), '{} is not the right dtype'.format(test_val)
except AssertionError:
the_type, the_value, the_traceback = sys.exc_info()
Upvotes: 1
Views: 657
Reputation: 36249
If you want to test whether a certain variable is of type int
, you can use isinstance(obj, int)
as you already do.
However you should never use assert
to validate any data, since these checks will be turned off when Python is invoked with the -O
command line option. assert
statements serve to validate your program's logic, i.e. to verify certain states that you can logically deduce your program should be in.
If you want to save whether your data conforms to some criteria, just store the True
or False
result directly, rather than asserting it and then excepting the error (beyond the reasons above, that's unnecessary extra work).
Upvotes: 2
Reputation: 37319
except AssertionError as err:
For more details like unpacking the contents of the exception, see towards the bottom of this block of the tutorial, the paragraph that begins "The except clause may specify a variable after the exception name."
Upvotes: 2