如果 Python 函数根据提供的参数返回不同的类型,它是否是好的代码风格?
def foo(bar):
if bar is None:
return None
elif bar == 1:
return 1*1
else:
return [b*b for b in bar]
Run Code Online (Sandbox Code Playgroud)
fooNone如果 bar 为 None 则返回
foo返回1如果bar == 1
foo返回一个列表,int如果 bar 是一个元组/整数列表
例子:
>> foo(None)
None
>> foo(1)
1
>> foo(1, 2, 3, 4)
[1, 4, 9, 16]
Run Code Online (Sandbox Code Playgroud)
返回None或 anint应该没问题,但是根据函数参数返回 anint或ints列表是否可以?您可能会争辩说这没问题,因为用户知道期望的返回类型并且不需要类型检查(在这种情况下我会说这不行),但有人可能会争辩说最好将函数拆分为两个函数,一个期待 aint并返回 an int,一个期待一个列表int并返回一个ints列表。
这完全取决于您的用例。这是标准库中的一个示例,其中结果的类型取决于输入的类型:
>>> import operator
>>> operator.add(1, 2)
3
>>> operator.add(1.0, 2.0)
3.0
Run Code Online (Sandbox Code Playgroud)
这种类型的行为通常是可以的,并且可以使用 进行记录@typing.overload。
下面是一个示例,其中结果的类型取决于输入的值:
>>> import json
>>> json.loads('1')
1
>>> json.loads('[1]')
[1]
Run Code Online (Sandbox Code Playgroud)
这种类型的行为通常保留用于序列化和反序列化,或者模糊类型/值边界的 API,astype例如 np.int_(3).astype(bool).
另一方面,这是一个明显设计不佳的函数示例:
from typing import Union # make sure to document the mixed return type
def is_even(x: int) -> Union[bool, str]:
if x % 2 == 0:
return True
else:
return "no"
Run Code Online (Sandbox Code Playgroud)
在不了解您的具体用例的情况下,很难在这里提供建议。
| 归档时间: |
|
| 查看次数: |
400 次 |
| 最近记录: |