简体   繁体   中英

mypy error with union of callable and callable generator and typevar

def decorator(
        wrapped: Union[
            Callable[[], T],
            Callable[[], Generator[T, None, None]]
        ]
) -> Callable[[], T]:
    def wrapper():
        value = wrapped()
        if inspect.isgenerator(value):
            return next(value)
        else:
            return value
    return wrapper


@decorator
def foo() -> Generator[str, None, None]:
    yield "bar"

The above code produces the following error in mypy

error: Argument 1 to "decorator" has incompatible type "Callable[[], Generator[str, None, None]]"; expected "Callable[[], Generator[<nothing>, None, None]]"

Is this a limitation in mypy or am I doing something wrong?

It is a bug indeed. After debugging, I've discovered that if you explicitly set T generic:

U = Union[int, float, str] # your target types here
T = TypeVar('T', U, None)

or

T = TypeVar('T', None, Any)

It works as expected. If I set Any , it has to be the second parameter, but with union or scalar types it is being tested against the first argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM