I have a decorator that takes a function and returns the same function with some added attributes:
import functools
from typing import *
def decorator(func: Callable) -> Callable:
func.attr1 = "spam"
func.attr2 = "eggs"
return func
How do I type hint the return value of decorator? I want the type hint to convey two pieces of information:
- the return value is a
Callable - the return value has attributes
attr1andattr2
If I write a protocol,
class CallableWithAttrs(Protocol):
attr1: str
attr2: str
then I lose Callable. And apparently I can't make the protocol inherit from Callable;
class CallableWithAttrs(Callable, Protocol):
attr1: str
attr2: str
mypy says:
error: Invalid base class "Callable"
On the other hand, if I just use Callable, I lose the information about the added attributes.
This is perhaps even more complicated when introducing type variables, i.e. when the decorator must return the same type of callable as the given function func, as pointed out by MisterMiyagi in the comments.
import functools
from typing import *
C = TypeVar('C', bound=Callable)
def decorator(func: C) -> C:
func.attr1 = "spam"
func.attr2 = "eggs"
return func
Now what do I do? I can't inherit from a type variable:
class CallableWithAttrs(C, Protocol):
attr1: str
attr2: str
error: Invalid base class "C"