函数参数解析(如果类型可以变化)

问题描述 投票:0回答:2

我有一个可以用布尔值

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))

并有一个通用的方法来处理这种情况?

python
2个回答
1
投票
正如 Python Zen 所说:“应该有一种 - 最好只有一种 - 明显的方法来做到这一点。” 据此,您不应该有两种调用函数的方法,它们执行相同的操作,但却相互冲突。相反,创建一个由接口提供的函数来请求并解析可能的 str 或 int 参数,例如:

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
    

-2
投票

bool(int(onoff))

 中,
bool
 并不是真正必要的,因为 if 语句会自动将其转换为布尔值。

此外,由于唯一的

False

整数是
0
,你可以轻松做到

onoff = onoff != "0"
但这并不会检查 onoff 是否为整数;如果不是 

True

,它只会返回 
0

© www.soinside.com 2019 - 2024. All rights reserved.