我有一个可以用布尔值
onoff
或字典request
来调用的函数。如果onoff
直接作为参数,它可以是True
、
False
或
None
。如果它来自
request
字典,那么
request["onoff"]
可以是整数或字符串(它来自 HTTP API 请求;注意:它已经被清理)。
def func(onoff=None, request=None):
if request is not None:
onoff = request.get("onoff")
if onoff is not None:
onoff = bool(int(onoff)) # works but it seems not very explicit
if onoff:
print("Turn On")
else:
print("Turn Off")
else:
print("onoff is None, so no modification")
func()
func(onoff=True) # True
func(request={"onoff": 1}) # True
func(request={"onoff": "1"}) # True
func(onoff=False) # False
func(request={"onoff": 0}) # False
func(request={"onoff": "0"}) # False
有没有办法避免这种习惯bool(int(onoff))
并有一个通用的方法来处理这种情况?
def request_func(request):
onoff = request.get("onoff")
if onoff is not None:
onoff = bool(int(onoff))
func(onoff, request['other_param'])
还有一个可以直接调用的,它总是需要 bool
参数:
def func(onoff=None, other_param=None):
if onoff is not None:
if onoff:
print("Turn On")
else:
print("Turn Off")
else:
print("onoff is None, so no modification")
这样每个函数都有一个特定的签名,并且您不会冒同时使用两种方式传递冲突参数的风险。
func(onoff=True) # True
request_func(request={"onoff": 1}) # True
request_func(request={"onoff": "1"}) # True
func(onoff=False) # False
request_func(request={"onoff": 0}) # False
request_func(request={"onoff": "0"}) # False
bool(int(onoff))
中,
bool
并不是真正必要的,因为 if 语句会自动将其转换为布尔值。此外,由于唯一的
False
整数是
0
,你可以轻松做到
onoff = onoff != "0"
但这并不会检查 onoff 是否为整数;如果不是 True
0