>>> bool(None)False>>> not NoneTrue
>>> bool([])False>>> not []True
>>> class MyFalsey(object):... def __bool__(self):... return False>>> f = MyFalsey()>>> bool(f)False>>> not fTrue
因此,当以以下方式测试变量时,要格外注意测试中包含或排除的内容:
def some_function(value=None):if not value:value = init_value()
try:# Equivalent to getattr() without specifying a default# value = getattr(some_obj, 'some_attribute')value = some_obj.some_attribute# Now you handle `None` the data hereif value is None:# Do something here because the attribute was set to Noneexcept AttributeError:# We're now handling the exceptional situation from here.# We could assign None as a default value if required.value = None# In addition, since we now know that some_obj doesn't have the# attribute 'some_attribute' we could do something about that.log_something(some_obj)
同样的,DOS:
try:value = some_dict['some_key']if value is None:# Do something here because 'some_key' is set to Noneexcept KeyError:# Set a defaultvalue = None# And do something because 'some_key' was missing# from the dict.log_something(some_dict)
上面的两个例子展示了如何处理对象和字典的情况。函数呢?同样的事情,但我们为此使用双星号关键字参数:
def my_function(**kwargs):try:value = kwargs['some_key']if value is None:# Do something because 'some_key' is explicitly# set to Noneexcept KeyError:# We assign the defaultvalue = None# And since it's not coming from the caller.log_something('did not receive "some_key"')
def my_function(value, param1=undefined, param2=undefined):if param1 is undefined:# We know nothing was passed to it, not even Nonelog_something('param1 was missing')param1 = None
if param2 is undefined:# We got nothing here eitherlog_something('param2 was missing')param2 = None
与字典
value = some_dict.get('some_key', undefined)if value is None:log_something("'some_key' was set to None")
if value is undefined:# We know that the dict didn't have 'some_key'log_something("'some_key' was not set at all")value = None
用一个物体
value = getattr(obj, 'some_attribute', undefined)if value is None:log_something("'obj.some_attribute' was set to None")if value is undefined:# We know that there's no obj.some_attributelog_something("no 'some_attribute' set on obj")value = None
def is_empty(element) -> bool:"""Function to check if input `element` is empty.
Other than some special exclusions and inclusions,this function returns boolean result of Falsy check."""if (isinstance(element, int) or isinstance(element, float)) and element == 0:# Exclude 0 and 0.0 from the Falsy set.return Falseelif isinstance(element, str) and len(element.strip()) == 0:# Include string with one or more empty space(s) into Falsy set.return Trueelif isinstance(element, bool):# Exclude False from the Falsy set.return Falseelse:# Falsy check.return False if element else True