在python3中,在NoneType
上使用>
或<
操作数将导致TypeError。
例如,当比较两个日期时,我可以使用:
a = datetime(...)
b = datetime(...)
if a < b:
// do something
但如果a = None
由于某种原因(例如,它是函数的结果(,则会导致:
'<' not supported between instances of 'NoneType' and 'DateTime'
在python2中,这将评估为True
。
如果a
和b
是变量,可以是datetime
或None
,如果其中一个值是None
,我想跳过比较,解决这一问题的最优雅方法是什么?
例如,以下方法有效,但感觉有更好的单线方法吗?
if a and b:
if a < b:
// do something
因为这里使用的是对象而不是数字,所以我选择简短而明确的:
if (a and b) and (a < b):
# Do something
如果a
或b
中的任何一个是None
,则它将短路,并且从不执行比较。
您可以使用or
运算符:
a = None
b = 1
int(a or 0) < b
输出:
True
如果a
是None
,则int(a or 0)
返回0
,否则将返回a
(如果a
是数字(。
更新:要解决更新后的问题:
if None not in [a,b]: # if neither values are None
# Do something
您可以使用扩展的if语句,但我通常更喜欢使用try
块。这最终变得非常可读,并且显式地处理TypeErrors
,同时还提供了一种相对方便的方式来处理可能出现的其他错误。
try:
if a < b:
do_the_thing()
except TypeError:
handle_bad_types()
import datetime
# a, b can be datetime objects, or None
a = datetime.datetime.now()
b = None
if a is not None and b is not None:
print("Neither values are None, do your operation here.")
else:
print("One or both the values are None, operation was not performed.")