python - 我可以使用 python 装饰器根据输入类型预处理输入和后处理输出吗?
问题描述
我有可以采用 aList
或 a 的函数str
。返回类型应与输入类型匹配。例如,如果给定 astr
函数应该返回 a 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
我可以使用装饰器进行这种轻微的预处理和后处理吗?
解决方案
是的,您可以使用这样的装饰器:
from typing import Union, List
def pre_and_post_processing(func):
def inner(a: Union[List, str]) -> Union[List, str]:
STR = isinstance(a, str)
a = list(a)
b = func(a)
return "".join(b) if STR else b
return inner
@pre_and_post_processing
def swap_first_and_last(a: List) -> List:
a[0], a[-1] = a[-1], a[0]
return a
print(swap_first_and_last("asd")) # -> dsa
print(swap_first_and_last(["asd", "ds", "sds"])) # -> ['sds', 'ds', 'asd']
请注意,该swap_first_and_last
函数现在获取并返回一个List
.
推荐阅读
- mysql - mysql过程if条件
- pixi.js - 在画布上制作缩放图像幻灯片
- javascript - VueJs 理解 v-model 和 v-on:click
- javascript - 为什么 .simulate("mouseover") 在 Jest / Enzyme 测试中不起作用?
- reactjs - 努力从api获取一些数据
- java - Kotlin 到 java 的转换 DefaultConstructorMarker 在 kotlin.jvm.internal 中不公开
- python - 我可以在循环中插入带有值列表的字典吗?
- sql - 如何计算同一列中的两个不同值并将这些计数输出到两个不同的列
- ajax - ajax请求成功后如何在另一个页面启动数据表?
- python - AWS QLDB ion_document 更新