实现协议的Python泛型类型

sve*_*cax 9 python generics protocols python-typing

对象 A、B ... 具有属性namespace,并且我有一个函数可以通过一组特定的属性值过滤此类对象的列表namespace

T = TypeVar('T')


def filter(seq: list[T], namespace_values: set[str]) -> list[T]:
    # Returns a smaller list containing only the items from
    # `seq` whose `namespace` are in `namespace_values`
    ...
Run Code Online (Sandbox Code Playgroud)

X这很有效,但它允许传递不具有该属性的类型的对象,namespace而不会出现任何检查错误。

然后我创建了一个协议并更改了函数以便使用该协议:


class Namespaced(Protocol):
    namespace: str

def filter(seq: list[Namespaced], namespace_values: set[str]) -> list[Namespaced]:
    # Returns a smaller list containing only the items from
    # `seq` whose `namespace` are in `namespace_values`
    ...
Run Code Online (Sandbox Code Playgroud)

现在,如果我传递一个列表X(这就是我想要的),我会收到一个检查错误,但我丢失了泛型:


list_of_a: list[A] = [a1, a2, a3]

output = filter(list_of_a, ['ns1', 'ns2'])

# output is list[Namespaced] instead of list[A]

Run Code Online (Sandbox Code Playgroud)

如何将泛型和协议结合起来,以便我的函数返回类型 T 的列表,并检查 的seq项目是否实现Namespaced协议?

我尝试了以下方法,但T丢失了。


def filter(seq: list[Namespaced[T]], namespace_values: set[str]) -> list[T]:
    # Returns a smaller list containing only the items from
    # `seq` whose `namespace` are in `namespace_values`
    ...

Run Code Online (Sandbox Code Playgroud)

干杯!

jua*_*aga 9

使用以协议作为绑定的绑定类型变量。考虑以下模块:

(py39) Juans-MacBook-Pro:~ juan$ cat test.py
Run Code Online (Sandbox Code Playgroud)

其中有:

from typing import TypeVar, Protocol
from dataclasses import dataclass

class Namespaced(Protocol):
    namespace: str


T = TypeVar("T", bound="Namespaced")

@dataclass
class Foo:
    namespace: str

@dataclass
class Bar:
    namespace: str
    id: int

def frobnicate(namespaced: list[T]) -> list[T]:
    for x in namespaced:
        print(x.namespace)
    return namespaced

result1 = frobnicate([Foo('foo')])
result2 = frobnicate([Bar('bar', 1)])

reveal_type(result1)
reveal_type(result2)
Run Code Online (Sandbox Code Playgroud)

然后 mypy 给出:

(py39) Juans-MacBook-Pro:~ juan$ mypy --strict test.py
test.py:27: note: Revealed type is "builtins.list[test.Foo*]"
test.py:28: note: Revealed type is "builtins.list[test.Bar*]"
Run Code Online (Sandbox Code Playgroud)