1

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()


John Stud
  • 1,506
  • 23
  • 46

2 Answers2

2

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."

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
2

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).

a_guest
  • 34,165
  • 12
  • 64
  • 118
  • This is interesting -- `However you should never use assert to validate any data` -- could you please elaborate on how this might look in code? – John Stud Jul 08 '21 at 21:04
  • @JohnStud What exactly do you mean? Without more context, it's difficult to give a concrete example. – a_guest Jul 08 '21 at 21:06
  • I want to validate data and you are strongly recommending to not use assertion to validate data, but instead store True/False results. What are you envisioning to yield those True/False results. In other words, what might I do differently, in code? Something like: `result1 = isinstance(test_val, int)` # yields True or False – John Stud Jul 08 '21 at 21:10
  • @JohnStud Well, I mean `try: assert X` and then `except AssertionError` means the only way you can arrive in the `except` block is that the previous `assert` statement raised which in turn it only did if `X` was `False`. Hence you get the same information by just looking at `X`. In your case this would be `isinstance(test_val, int)`. The `AssertionError` gives you no information beyond what you already have. – a_guest Jul 08 '21 at 21:22