有没有一种方法可以使用Python类型提示为函数参数定义几种类型?

时间:2020-06-01 11:51:55

标签: python type-hinting

我的情况大致如下所示:

from typing import List, Iterable, Iterator

class MyCustomObject:
    pass

class MyIterableClass:
    def __init(self, object_list: List[MyCustomObject]):
        self.object_list = object_list

    def __iter__(self) -> Iterator[MyCustomObject]:
        for obj in self.object_list:
            yield obj

class MyCustomObject2:
    pass

class MyIterableClass2:
    def __init(self, object_list: List[MyCustomObject2]):
        self.object_list = object_list

    def __iter__(self) -> Iterator[MyCustomObject2]:
        for obj in self.object_list:
            yield obj

# my_function could accept any Iterable[MyCustomObject]
def my_function(iterable: MyIterableClass):
    # This iterable could be Iterable[MyCustomObject], but the type checking seems to fail below
    for obj in iterable:
        do_something(obj)

my_function(MyIterableClass())
my_function(MyIterableClass2()) # This fails to check the type if I use Iterable[MyCustomObject] in my_function type hint

我知道我可以为此使用Iterable [MyCustomObject],但是如果我尝试使用错误的类型(例如,自定义类会产生一些错误),则类型检查似乎会在PyCharm中中断,并且不会引发任何警告。其他类型)。

所以我很好奇,有没有一种方法可以定义几种类型作为类型提示(即List [MyCustomObject]和MyIterableClass),以便类型检查器正常工作?

0 个答案:

没有答案