we have multiple partial-like functions with same type annotation with args and kwargs like:
JavaScript
x
12
12
1
def fruit(fruit_name: str, fruit_class: Type, arg1: int, arg2: float, arg3: tuple):
2
pass
3
4
def apple(*args, **kwargs):
5
return fruit("apple", *args, **kwargs)
6
7
def orange(*args, **kwargs):
8
return fruit("orange", *args, **kwargs)
9
10
def banana(*args, **kwargs):
11
return fruit("banana", *args, **kwargs)
12
can I somehow create a template for functions apple
, orange
, banana
and assign it to them?
I thought about Protocol
with __call__
definition, but it is unclear how to assign it to functions
Advertisement
Answer
Rather than a function, you can use functools.partial
:
JavaScript
1
15
15
1
from typing import Callable, Type
2
from functools import partial
3
4
Fruit = # whatever fruit returns
5
# type of fruit(), but without the initial string parameter
6
FruitMaker = Callable[[Type, int, float, tuple], Fruit]
7
8
def fruit(fruit_name: str, fruit_class: Type, arg1: int, arg2: float, arg3: tuple) -> Fruit:
9
10
11
12
apple: FruitMaker = partial(fruit, "apple")
13
orange: FruitMaker = partial(fruit, "orange")
14
banana: FruitMaker = partial(fruit, "banana")
15
Another possibility would be to refactor fruit
to take a name, and return a function that closes over the fruit name.
JavaScript
1
9
1
def fruit_maker(fruit_name: str) -> FruitMaker:
2
def fruit(fruit_class: Type, arg1: int, arg2: float, arg3: tuple):
3
4
return fruit
5
6
apple = fruit_maker("apple")
7
orange = fruit_maker("orange")
8
banana = fruit_maker("banana")
9