What is the best way to execute code when a test does not raise an error in Python?

Viewed 124

Background story: I am processing some messy data sheets made in Excel. Reading this with pandas (preferable) does sometimes conserve the Excel data type of the cells. As all entries I would like to process have a value in a certain column that can be converted to an integer, I would like to execute a code block when this column can be converted (i.e. does not throw an error). I know there are some ways to work around this problem, but I would like to know what you would do if you would like to execute code when no error is returned from a statement without the try/except statement.

The try/except block is what I came up with so far:

try:
    int(x)

    # Big code chunk goes here
    ....

    # Exception can be found much further down in the code
except ValueError:
    pass

This feels a bit odd to me. To make it a bit more readable the code chunk could be placed in a function, but what I am really looking for is something like this:

if int(x) == NoError:
    # Lets go ahead with the code chunk
    ....

Are there nice ways of implementing something like this for a general use case?

3 Answers

What you possibly are looking for is a try-except-else block

try:
    int(x)
except ValueError:
    ...
else:
    # No error

As you are working with pandas, you might be able to use pandas.to_numeric.

It explicitly handles errors:

errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

If ‘raise’, then invalid parsing will raise an exception.

If ‘coerce’, then invalid parsing will be set as NaN.

If ‘ignore’, then invalid parsing will return the input.

Use contextlib.suppress:

from contextlib import suppress

with suppress(ValueError):
    int(x)
    # Big code chunk goes here
    ...
Related