简洁的整体浮动检查

时间:2021-04-29 16:24:24

标签: python exception integer typechecking

我想改进我的编码。

最近我在思考我在 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 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 更灵活,更能反映检查的意图 - 为不接受输入的原因提供灵活性和透明度。

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

提前致谢!

1 个答案:

答案 0 :(得分:2)

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

您无需担心 try 中的周围事物,除非您首先检查它是否是 intfloat 的实例:

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 是第一个,如果因为我传入一个字符串而没有通过,它永远不会尝试将其转换为浮点数。

相关问题