问题一:
我想使用 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;它的值总是 int) .
选项 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])
请您参考如下方法:
TypeVar 的目的是在泛型类或独立泛型函数的声明中充当占位符。
您在问题 1 中寻找的内容可能大致如下:
import typing as tg
from collections import Counter
class Bow(Counter, tg.Mapping[str, int]):
pass
要制作一个通用的“任意元素袋”( python ),您可以使用:
import typing as tg
from collections import Counter
S = tg.TypeVar('S') # STUFF
class Boas(Counter, tg.Mapping[S, int]):
pass
在这两种情况下,都不需要类主体: 所有功能都将从 Counter 继承,并且 从以下意义上讲,所有类型都将派生自 tg.Mapping: 例如,如果您声明
def foo(bag: Bow, what):
n = bag[what]
#...
一个静态类型检查器(前提是Counter有一个 stub 文件 或者在 Counter 实现中输入注解) 应该能够推断出 n 将是 int 并且 可能得出结论或假设what 将是str。 动态类型检查器(通过装饰foo激活, PyPI typecheck-decorator 包将很快提供 合适的东西) 当调用 foo 时,可能会查看实际的 bag 对象 并检查部分或全部键为 str 和 对应的值为int。
