Tur*_*rmy 5 python type-hinting python-3.x
我正在编写一个方法,它接受类型元组并返回一个对象,该对象是这些类型之一的实例或None. 我想输入提示该函数以表明它返回传递的类型之一的实例或None作为联合。但是,我的 typehint 暗示返回类型是元组中元素的最低公共基类的联合,或者None。我怎样才能解决这个问题?
就我而言,这些类型碰巧有一个共享基类,但理想情况下我想要一个适用于任何类型元组的解决方案。
from typing import Union, Optional, TypeVar
class Base: ...
class A(Base): ...
class B(Base): ...
class C(Base): ...
def get_data() -> tuple[Base, ...]:
return (A(), C())
T = TypeVar("T", bound=Base)
# I have also tried typehinting the return value as Optional[Union[T]] but
# that didn't change anything.
def find_instance(types: tuple[type[T], ...]) -> Optional[T]:
for element in get_data():
if isinstance(element, types):
return element
return None
def find_instance2(types: tuple[T, ...]) -> Optional[T]:
for element in get_data():
if isinstance(element, types):
return element
return None
# The final typehints I'm looking for
a: Optional[Base] = find_instance((Base,)) # Inferred as Optional[Base]
b: Optional[Union[B, C]] = find_instance((B, C)) # Also inferred as Optional[Base]
# Both c and d are inferred as Optional[Type[Base]]
c: Optional[Base] = find_instance2((Base,))
d: Optional[Union[B, C]] = find_instance2((B, C))
Run Code Online (Sandbox Code Playgroud)
使用mypy检查上面的代码会出现以下错误:
test.py:18: error: Incompatible return value type (got "Base", expected "Optional[T]")
test.py:23: error: Argument 2 to "isinstance" has incompatible type "Tuple[T, ...]"; expected "Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]"
test.py:24: error: Incompatible return value type (got "Base", expected "Optional[T]")
test.py:29: error: Incompatible types in assignment (expression has type "Optional[Base]", variable has type "Union[B, C, None]")
test.py:32: error: Value of type variable "T" of "find_instance2" cannot be "Type[Base]"
test.py:32: error: Incompatible types in assignment (expression has type "Optional[Type[Base]]", variable has type "Optional[Base]")
test.py:33: error: Value of type variable "T" of "find_instance2" cannot be "Type[Base]"
test.py:33: error: Incompatible types in assignment (expression has type "Optional[Type[Base]]", variable has type "Union[B, C, None]")
Found 8 errors in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2072 次 |
| 最近记录: |