![](/img/trans.png)
[英]MyPy - Incompatible types in assignment (expression has type None, variable has type X)
[英]Mypy complains about incompatible type when variable type is subset of expected type
嘗試構建一個xarray
Dataset
,我們在其中構建 arguments “coords”和“attrs”的輸入,然后將其傳遞給構造函數:
coordinates = {"time": ("time", time_coordinates)}
attributes = {"some_flag": False}
...
ds = xr.Dataset(data_vars=variables, coords=coordinates, attrs=attributes)
讓我感到困惑的是 mypy 的mypy
針對此代碼運行:
error: Argument "coords" to "Dataset" has incompatible type "Dict[str, Tuple[str, Any]]"; expected "Optional[Mapping[Hashable, Any]]"
error: Argument "attrs" to "Dataset" has incompatible type "Dict[str, bool]"; expected "Optional[Mapping[Hashable, Any]]"
dict
不是Mapping
嗎? 而且str
也不是Hashable
嗎? 無論如何,不是Any
類型的Tuple
和bool
嗎? 我在這里對 mypy 和/或 Python 類型提示有什么不明白的地方?
使用來自Selcuk的信息,我發現了這個有點冗長的解決方案,如mypy 文檔中所述:由於Mapping
的鍵是不變的,因此需要明確提示str
的類型為Hashable
。 (雖然字符串是Hashable
的子類型,但Mapping
的鍵不是協變的,不允許子類型。)。 或者,正如塞爾丘克在他的評論中所說:
str
是Hashable
,但由於dict
是可變數據類型,因此您必須為鍵傳遞完全相同的類型,而不是子類型。 被調用的 function 可能會在傳遞的參數中添加另一個Hashable
鍵,從而破壞源。
coordinates: Dict[Hashable, Tuple[str, Any]] = {
"time": ("time", time_coordinates)
}
attributes: Dict[Hashable, Any] = {"some_flag": False}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.