首页 > 解决方案 > 简洁的整体浮动检查

问题描述

我想改进我的编码。

最近,我正在思考一些我作为 Python 构造函数的一部分编写的代码。构造函数只允许整数或整数浮点数。我想出了一些方法来检查这个,但想把它放在这里看看是否有更简洁的方法来做这个双重异常检查。

方法一: 试试,除外。

try:
  if not float(x).is_integer:
    raise ValueError('X must be a whole number float')
except:
  raise ValueError('X must be an int or a float'):

方法2: 双if。

if not isinstance(x, (int, float)):
    raise ValueError('X must be an int or whole number float.')

elif not float(x).is_integer():
    raise ValueError('X must be a whole number float.')

方法 3:禁止任何非整数。

if not isinstance(x, int):
    raise ValueError('X must be an int.')

我想看看最好的方法是什么。方法 3 将节省一些代码行,尽管它对代码增加了不必要的限制。方法 1 和 2 更灵活,更能反映检查的意图——为不接受输入的原因提供灵活性和透明度。

有没有更简洁的方法来执行上述检查?

提前致谢!

标签: pythonexceptionintegertypechecking

解决方案


有一种更紧凑的检查方式。首先考虑您要检查的是什么。你关心两件事:整数或整数浮点数。幸运的是,Python 条件是短路评估orand这意味着如果其中一个条件“短路”其余条件,它们不需要评估整个条件。

您无需担心 try 中的周围事物 - 除非您首先检查它是否是 anint或的实例float

In [37]: class T:
    ...:     def __init__(self, val):
    ...:         if not (isinstance(val, (int, float)) and float(val).is_integer()):
    ...:             raise Exception(f'{val} must be a whole number float or integer')
    ...:

In [38]: T(12)
Out[38]: <__main__.T at 0x2605d2174f0>

In [39]: T(14.)
Out[39]: <__main__.T at 0x2605d1dda60>

In [40]: T('hello')  # Raises exception

因为isinstance是第一个,如果因为我传入一个字符串而没有通过,它永远不会尝试将其转换为浮点数。


推荐阅读