简体   繁体   English

实例检查良好做法之前没有检查?

[英]None check preceding an isinstance check good practice?

Is it good practice to test for not None preceding an isinstance check in Python? 在Python中执行isinstance检查之前是否测试None是否是一种好习惯? For example: 例如:

if x is not None and isinstance(x, (int, float)):
    # Some code over here 
    pass

Or can I do without and is this sufficient? 还是我可以没有,这是否足够?

if isinstance(x, (int, float)):
    # Some code over there 
    pass

To answer your question, doing a is not None check is unnecessary, because - 要回答您的问题,不必进行a is not None检查,因为-

>>> isinstance(None, (int, float))
False

Meaning, if x is None , then the isinstance condition would return False anyway, making the x is not None check redundant. 这意味着,如果xNone ,则isinstance条件无论如何都将返回False ,从而使x is not None检查冗余。 So, in summary, 所以总而言之

if isinstance(x, (int, float)):
    ...

Works just as well. 效果也一样。


Furthermore, if you want to test whether an object is numeric in nature, a simpler way to do so would be using the numbers module - 此外,如果您想测试对象是否本质上是数字的,则更简单的方法是使用numbers模块-

import numbers
if isinstance(x, numbers.Number):
    ...

Note that numbers.Number tests all numeric objects from the very root of the hierarchy. 请注意, numbers.Number从层次结构的最根开始测试所有数字对象。 This also includes complex numbers, so if that isn't what you want, you can test with numbers.Real to numbers.Rational instead. 这也包括复数,因此,如果这是不是你想要的,你可以测试numbers.Realnumbers.Rational代替。

Python 2.7.14 (default, Sep 20 2017, 01:25:59) 
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(None, (int, float))
False
>>> 

It raises no error, so I would actually prefer the version without the 'is None' check, as it is just less code. 它不会引起任何错误,所以我实际上更喜欢没有'is None'检查的版本,因为它的代码更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM