物件 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`
...
這很有效,但它允許傳遞沒有任何檢查錯誤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`
...
現在,如果我通過一個串列X(這是我想要的),我會收到一個檢查錯誤,但是我丟失了泛型:
list_of_a: list[A] = [a1, a2, a3]
output = filter(list_of_a, ['ns1', 'ns2'])
# output is list[Namespaced] instead of list[A]
如何組合泛型和協議,以便我的函式回傳 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`
...
干杯!
uj5u.com熱心網友回復:
使用系結型別變數和協議作為系結。考慮以下模塊:
(py39) Juans-MacBook-Pro:~ juan$ cat test.py
其中有:
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)
然后 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*]"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389720.html
下一篇:Typescript通用介面陣列
