3

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?

Jan Willem
  • 820
  • 1
  • 6
  • 24
  • Does [this](https://stackoverflow.com/questions/6911999/execute-if-no-exception-thrown) answer your question? – Georgy Kopshteyn Jun 08 '21 at 17:29
  • 1
    I'm not clear on what you want: continuing with no error is the normal mode of operation. The `else` clause is in any tutorial on try/except. As such, your needs are unclear. – Prune Jun 08 '21 at 17:30
  • You could always try `str.isnumeric` – M Z Jun 08 '21 at 17:31
  • 1
    The try/except is the normal way to handle this. You could bury it in a function that catches the error and returns, say, `None` and use that as the sentinel, but I think the try/except is more clear. – tdelaney Jun 08 '21 at 17:43

3 Answers3

4

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

try:
    int(x)
except ValueError:
    ...
else:
    # No error
lonetwin
  • 971
  • 10
  • 17
3

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.

nocibambi
  • 2,065
  • 1
  • 16
  • 22
0

Use contextlib.suppress:

from contextlib import suppress

with suppress(ValueError):
    int(x)
    # Big code chunk goes here
    ...
Terry Spotts
  • 3,527
  • 1
  • 8
  • 21
  • This will execute the code always right? I want to check if it throws an error. If it does I don't want to execute anything. – Jan Willem Jun 08 '21 at 17:34