我有以下代码:
from typing import TypeVar, Any, Generic
class Foo:
...
class Bar(Generic[FooT]):
def __init__(self, foo: FooT):
self._foo = foo
FooT = TypeVar('FooT', bound=Foo)
T = TypeVar('T')
def func(a: FooT | T) -> Bar[FooT] | T:
if isinstance(a, Foo):
return Bar(a)
return a
def my_other_func(a: Foo) -> None:
func(a)
func
采用 Foo
子类并返回 Bar
包装该 Foo
对象,或返回未更改的输入我想我可以将其输入为
def func(a: FooT | T) -> Bar[FooT] | T:
但是如果我运行
mypy
,我会得到
main.py:18: error: Argument 1 to "Bar" has incompatible type "Foo"; expected "FooT" [arg-type]
main.py:22: error: Argument 1 to "func" has incompatible type "Foo"; expected "Never" [arg-type]
Found 2 errors in 1 file (checked 1 source file)
我也不明白。
我应该如何输入?
使用
typing.overload
:
from typing import TypeVar, Generic
class Foo:
...
FooT = TypeVar('FooT', bound=Foo)
class Bar(Generic[FooT]):
def __init__(self, foo: FooT):
self._foo = foo
T = TypeVar('T')
@overload
def func(a: FooT) -> Bar[FooT]:
...
@overload
def func(a: T) -> T:
...
def func(a):
if isinstance(a, Foo):
return Bar(a)
return a
def my_other_func(a: Foo) -> None:
func(a)
本质上,
Callable[[FooT|T], Bar[FooT]|T]
与Callable[[FooT], Bar[FooT]] | Callable[[T], T]
不同。 typing.overload
让您可以定义后者而不是前者。