【问题标题】:How to define a TypeVar for Counter[str] with Python 3.5's type hinting如何使用 Python 3.5 的类型提示为 Counter[str] 定义 TypeVar
【发布时间】: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


    【解决方案1】:

    TypeVar 的目的是在泛型类或独立泛型函数的声明中充当占位符。

    您似乎在问题 1 中寻找的内容可能大致如下:

    import typing as tg
    from collections import Counter
    
    class Bow(Counter, tg.Mapping[str, int]):
        pass
    

    要制作一个通用的“一袋任意东西”(蟒蛇),您可以使用:

    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

    【讨论】:

    • 这正是我目前遇到的问题,除了我特别不希望为 Counter[str] 类型创建类型别名/名称。这也可能吗?
    猜你喜欢
    • 2020-12-24
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2022-07-03
    • 2022-08-18
    • 2021-01-13
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多