当测试未在 Python 中引发错误时,执行代码的最佳方式是什么?
What is the best way to execute code when a test does not raise an error in Python?
背景故事:我正在处理一些在Excel中制作的乱七八糟的数据表。使用 pandas(最好)读取此内容有时确实会保留单元格的 Excel 数据类型。由于我要处理的所有条目在特定列中都有一个可以转换为整数的值,因此我想在可以转换该列时执行代码块(即不抛出错误)。我知道有一些方法可以解决这个问题,但我想知道如果您想在没有 try/except 语句的语句中没有返回错误的情况下执行代码 ,您会怎么做.
try/except 块是我到目前为止想到的:
try:
int(x)
# Big code chunk goes here
....
# Exception can be found much further down in the code
except ValueError:
pass
我觉得这有点奇怪。为了使其更具可读性,可以将代码块放在一个函数中,但我真正想要的是这样的:
if int(x) == NoError:
# Lets go ahead with the code chunk
....
是否有针对一般用例实现此类功能的好方法?
您可能正在寻找的是 try-except-else
区块
try:
int(x)
except ValueError:
...
else:
# No error
from contextlib import suppress
with suppress(ValueError):
int(x)
# Big code chunk goes here
...
当您使用 pandas 时,您或许可以使用 pandas.to_numeric
。
它明确地处理错误:
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.
背景故事:我正在处理一些在Excel中制作的乱七八糟的数据表。使用 pandas(最好)读取此内容有时确实会保留单元格的 Excel 数据类型。由于我要处理的所有条目在特定列中都有一个可以转换为整数的值,因此我想在可以转换该列时执行代码块(即不抛出错误)。我知道有一些方法可以解决这个问题,但我想知道如果您想在没有 try/except 语句的语句中没有返回错误的情况下执行代码 ,您会怎么做.
try/except 块是我到目前为止想到的:
try:
int(x)
# Big code chunk goes here
....
# Exception can be found much further down in the code
except ValueError:
pass
我觉得这有点奇怪。为了使其更具可读性,可以将代码块放在一个函数中,但我真正想要的是这样的:
if int(x) == NoError:
# Lets go ahead with the code chunk
....
是否有针对一般用例实现此类功能的好方法?
您可能正在寻找的是 try-except-else
区块
try:
int(x)
except ValueError:
...
else:
# No error
from contextlib import suppress
with suppress(ValueError):
int(x)
# Big code chunk goes here
...
当您使用 pandas 时,您或许可以使用 pandas.to_numeric
。
它明确地处理错误:
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.