问题1:
我想使用Python3.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:
...问题是,我不知道如何使计数器接受它的键的类型参数(在本例中是str;它的值总是ints)。
备选案文1:
由于计数器是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)不过,这也不太令人满意,因为它没有强制执行计数器上的键类型。
有什么正确的方法来处理这种情况吗?如果是,那又是什么呢?
问题2:
如果我正在创建我自己的类,我如何让它接受一个泛型类型参数?因此,如果我在一个名为Foo的模块中声明了一个类my_module,我将如何使其合法化:
from typing import TypeVar
from my_module import Foo
FooTypeAlias = TypeVar('FooTypeAlias', Foo[str])发布于 2016-01-22 10:29:14
TypeVar 的目的是在泛型类或独立泛型函数的声明中充当占位符。
您在问题1中似乎要查找的内容可能大致如下:
import typing as tg
from collections import Counter
class Bow(Counter, tg.Mapping[str, int]):
pass和来制作一个通用的“任意的东西包”(boas),您可以使用:
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或Counter实现中有类型注释的存根文件),应该能够推断n将是int,并可能得出或假定what将是str。--动态类型检查器(通过装饰foo激活,PyPI typecheck-decorator包将很快提供合适的东西)可能会在调用foo时查看实际的bag对象,并检查要为str的部分或全部密钥和对应的int值。
https://stackoverflow.com/questions/34562113
复制相似问题