-
Hello I have code such as the following: from typing import Callable, TypeVar
C = TypeVar('C', bound='Callable[[str], None]')
def do_nothing(func: C) -> C:
return func
class StrSubclass(str):
pass
@do_nothing
def test(arg: StrSubclass) -> None:
pass But this causes the following error:
How would I type this code? I've tried both I could reproduce this with MyPy here so it doesn't seem like a bug with Pyright. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Parameters within callables are implicitly contravariant, which is why you're seeing the error. Think about it this way. The function The workaround is to either change the bound type in |
Beta Was this translation helpful? Give feedback.
Parameters within callables are implicitly contravariant, which is why you're seeing the error.
Think about it this way. The function
test
requires that the caller pass aStrSubclass
instance as the first argument. ButC
is bound to a callback that accepts astr
. If the decoratordo_nothing
were to call this callback with astr
argument, it wouldn't satisfy the type requirements oftest
.The workaround is to either change the bound type in
C
to accept aStrSubclass
or changetest
to accept astr
argument.