[英]Mypy can't infer type from TypedDict.get(Optional[key], str)
[英]mypy does not infer generic type T with Optional[Any]
我對 mypy 和通用 T 參數有疑問。 我正在使用 sqlalchemy 會話get()方法從數據庫中檢索某些內容(代碼有效)。 我正在注入 (self.model=model) 我在其他地方定義的一個 SqlalchemyORM 模型。
Mypy 給我這條信息:
Variable "my_project.repositories.sql_repo.Foo.Optional" is not valid as a type [valid-type]mypy
See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliasesmypy
T = TypeVar("T")
class Foo(Generic[T]):
def __init__(self, model: Type[T], db: db_session) -> None:
super().__init__()
self.model = model
self.db = db
def get_by_id(self, item_id: int) -> Optional[T]:
return self.session().get(self.model,item_id)
導入時出錯,我不小心在我的 class 中導入了“from typing import Optional”。當然導入應該在頂層。 請注意,我仍然不完全理解 mypy 錯誤的含義。
# ..... IMPORT SHOULD BE AT THE TOP ...
from typing import Optional
# .............................
T = TypeVar("T")
class Foo(Generic[T]):
# ..... HERE WAS THE ERROR ...
from typing import Optional
# .............................
def __init__(self, model: Type[T], db: db_session) -> None:
super().__init__()
self.model = model
self.db = db
def get_by_id(self, item_id: int) -> Optional[T]:
return self.session().get(self.model,item_id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.