【发布时间】:2021-05-04 03:50:31
【问题描述】:
我的函数可以采用List 或str。返回类型应与输入类型匹配。例如,如果给定 str,则函数应返回 str。
这是一个玩具例子来说明这一点:
def swap_first_and_last(a: Union[List, str]) -> Union[List, str]:
# Not in-place.
STR = isinstance(a, str)
a = list(a)
a[0], a[-1] = a[-1], a[0]
return "".join(a) if STR else a
这是一个实际的例子:
def next_permutation(a: Union[List, str]) -> Union[List, str]:
"""
Not in-place.
Returns `None` if there is no next permutation
(i.e. if `a` is the last permutation).
The type of the output is the same as the type of the input
(i.e. str input -> str output).
"""
STR = isinstance(a, str)
a = list(a)
N = len(a)
i = next((i for i in reversed(range(N-1)) if a[i] < a[i + 1]), None)
if i is None:
return None
j = next(j for j in reversed(range(i+1, N)) if a[j] >= a[i])
a[i], a[j] = a[j], a[i]
a[i + 1:] = reversed(a[i + 1:])
return "".join(a) if STR else a
如您所见,只有几行专门用于处理str 输入与List 输入,即:
# preprocess
STR = isinstance(a, str)
a = list(a)
# main logic
...
# postprocess
return "".join(a) if STR else a
我可以使用装饰器来做这种轻微的预处理和后处理吗?
【问题讨论】:
-
不完全是您所追求的,但您知道
singledispatch模块中的singledispatch装饰器吗?
标签: python overloading decorator typing