[英]How to set a class method return typing dynamically from a class property
我在我的一個寵物項目中工作,發現了這個小問題。 我想在基數 class 中使用類型,問題是 class 方法的返回類型由子類設置的字段定義。 這是我的基地 class
class BaseRepository(metaclass=RequiredAttributes('model')):
model = None # The subclasses have to define the this field with a class type.
# All the class methods will return objects of the same
# type as this field.
def get(self, id) -> ??:
# return an object of the type defined in mode
...
class UserRepo(BaseRepository): # subclass
model = User # class type
...
我想將get
function 的類型設置為與 model 字段中定義的 object 類型相同。
關於如何完成這樣的事情有什么建議嗎?
如果沒有元類,這將傳遞 MyPy ,它能夠正確地推斷出x
是User
類型。 我無法使用元類對其進行測試,因為我沒有您的元類定義。 該解決方案使用參數化的Generic
作為基礎 class,這允許您向類型檢查器斷言 class 中的不同方法將具有相同的參數和返回參數類型。 Django 的存根文件中使用了類似的技術。
注意如果您使用的是 Python <= 3.8,則您必須從typing
模塊導入Type
並使用Optional[Type[M]]
而不是Optional[type[M]]
作為model
注釋。
from typing import Optional, Generic, TypeVar
M = TypeVar('M')
class BaseRepository(Generic[M], metaclass=RequiredAttributes('model')):
model: Optional[type[M]] = None # The subclasses have to define the this field with a class type.
# All the class methods will return objects of the same
# type as this field.
def get(self, id: int) -> M: ...
# return an object of the type defined in mode
class User:
pass
class UserRepo(BaseRepository[User]): # subclass
model = User # class type
x = UserRepo().get(1)
reveal_type(x) # Revealed type is "__main__.User*"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.