部分函数的类型注解

Type annotation for partial functions

我们有多个类似部分的函数,它们具有相同类型的注释,带有 args 和 kwargs,例如:

def fruit(fruit_name: str, fruit_class: Type, arg1: int, arg2: float, arg3: tuple):
    pass
    
def apple(*args, **kwargs):
    return fruit("apple", *args, **kwargs)
    
def orange(*args, **kwargs):
    return fruit("orange", *args, **kwargs)
    
def banana(*args, **kwargs):
    return fruit("banana", *args, **kwargs)

我能否以某种方式为函数 appleorangebanana 创建模板并将其分配给它们? 我考虑过 Protocol__call__ 定义,但不清楚如何将其分配给函数

“构建器”模式可能适合您:

class Fruit: pass
class FruitBuilder:
    def __init__(self, fruit_name: str):
        pass
    def build(self, fruit_class: type, arg1: int, arg2: float, arg3: tuple) -> Fruit:
        pass

class AppleBuilder(FruitBuilder):
    def __init__(self):
        super().__init__("apple")

class OrangeBuilder(FruitBuilder):
    def __init__(self):
        super().__init__("orange")

AppleBuilder().build(...)

您可以使用 functools.partial:

而不是函数
from typing import Callable, Type
from functools import partial

Fruit = ...  # whatever fruit returns
# type of fruit(), but without the initial string parameter
FruitMaker = Callable[[Type, int, float, tuple], Fruit]

def fruit(fruit_name: str, fruit_class: Type, arg1: int, arg2: float, arg3: tuple) -> Fruit:
    ...


apple: FruitMaker = partial(fruit, "apple")
orange: FruitMaker = partial(fruit, "orange")
banana: FruitMaker = partial(fruit, "banana")

另一种可能性是重构fruit取一个名字,return一个关闭水果名字的函数。

def fruit_maker(fruit_name: str) -> FruitMaker:
    def fruit(fruit_class: Type, arg1: int, arg2: float, arg3: tuple):
        ...
    return fruit

apple = fruit_maker("apple")
orange = fruit_maker("orange")
banana = fruit_maker("banana")