【发布时间】:2016-04-06 08:26:24
【问题描述】:
问题一:
我想使用 Python 3.5 的类型提示语法定义一个词袋类型别名,类似于:
from collections import Counter
from typing import TypeVar
# define bag-of-words type
Bow = TypeVar('Bow', Counter[str])
def process_bag_of_words(bag_of_words: Bow) -> Bow:
...
问题是我不知道如何让 Counter 接受其键的类型参数(在本例中为 str;它的值始终为 ints)。
选项 1:
由于 counter 是 dict 的子类,因此替代方案可能类似于:
from typing import TypeVar, Dict
# define bag-of-words type
Bow = TypeVar('Bow', Dict[str, int])
虽然这并不能确保我使用的是 Counter 而不是 Dict。
选项 2:
另一种选择是将Bow 定义为简单的Counter 类型,如下所示:
from collections import Counter
from typing import TypeVar
# define bag-of-words type
Bow = TypeVar('Bow', Counter)
不过,这也不是很令人满意,因为它不会强制 Counter 上的键类型。
有没有正确的方法来处理这种情况?如果有,是什么?
问题 2:
如果我正在创建自己的类,我怎么能让它接受泛型类型参数?因此,如果我在一个名为 my_module 的模块中声明了一个类 Foo,我将如何使其合法:
from typing import TypeVar
from my_module import Foo
FooTypeAlias = TypeVar('FooTypeAlias', Foo[str])
【问题讨论】:
标签: python python-3.x annotations type-hinting