我希望能夠定義子類的子類的內容typing.Iterable必須是什么。型別提示對于這個專案至關重要,所以我必須找到一個可行的解決方案
這是我已經嘗試過的和我想要的代碼:
# The code I'm writing:
from typing import TypeVar, Iterable
T = TypeVar('T')
class Data:
pass
class GeneralPaginatedCursor(Iterable[T]):
"""
If this type pf cursor is used by an EDR a specific implementation has to be created
Handle paginated lists, exposes hooks to simplify retrieval and parsing of paginated data
"""
# Implementation
pass
###########
# This part is supposed to be written by different developers on a different place:
class PaginatedCursor(GeneralPaginatedCursor):
pass
def foo() -> GeneralPaginatedCursor[Data]:
"""
Works great
"""
pass
def bar() -> PaginatedCursor[Data]:
"""
Raises
Traceback (most recent call last):
.
.
.
def bar(self) -> PaginatedCursor[Data]:
File "****\Python\Python38-32\lib\typing.py", line 261, in inner
return func(*args, **kwds)
File "****\Python\Python38-32\lib\typing.py", line 894, in __class_getitem__
_check_generic(cls, params)
File "****\Python\Python38-32\lib\typing.py", line 211, in _check_generic
raise TypeError(f"{cls} is not a generic class")
"""
pass
我不想讓未來的其他開發人員繼承它,Iterable因為如果有人錯過它,一切都會崩潰。
我在這里發現了完全相同的問題: https ://github.com/python/cpython/issues/82640 但是沒有答案。
uj5u.com熱心網友回復:
唯一的要求是GeneralPaginatedCursor定義__iter__回傳一個Iterable值(即帶有__next__方法的東西)。
您看到的錯誤發生是因為,因為在 ,GeneralPaginatedCursor中是通用的T,所以也PaginatedCursor應該是。
class PaginatedCursor(GeneralPaginatedCursor[T]):
pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519876.html
上一篇:如何避免NHibernate中nvarchar(max)列的極慢異步讀取
下一篇:如何實作通用的“選項”引數?
