You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何list[list[str]]无法匹配list[HashableList[Hashable]]?subplot_mosaic类型检查报错

Matplotlib subplot_mosaic 类型检查问题解析

问题场景

使用matplotlib.pyplot.subplot_mosaic时触发类型检查报错,生成mosaic布局和per_subplot_kw的函数如下:

def create_mosaic(num_rows):
    def base_panel(idx):
        return [f"rgb{idx}", f"hist{idx}", f"polar{idx}"]

    mosaic = list()
    per_subplot_kw = dict()

    for i in range(num_rows):
        mosaic.append(base_panel(i))
        per_subplot_kw[f"polar{i}"] = dict(projection="polar")
    return mosaic, per_subplot_kw

调用代码:

mosaic, kw = create_mosaic(3)
plt.subplot_mosaic(mosaic, per_subplot_kw=kw)

触发的类型错误:

Diagnostics:
1. No overloads for "subplot_mosaic" match the provided arguments [reportCallIssue]
2. Argument of type "list[list[str]]" cannot be assigned to parameter "mosaic" of type "list[HashableList[Hashable]]" in function "subplot_mosaic"
   "list[list[str]]" is not assignable to "list[HashableList[Hashable]]"
     Type parameter "_T@list" is invariant, but "list[str]" is not the same as "HashableList[Hashable]"
     Consider switching from "list" to "Sequence" which is covariant [reportArgumentType]
3. Argument of type "dict[str, dict[str, str]]" cannot be assigned to parameter "per_subplot_kw" of type "dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None" in function "subplot_mosaic"
   Type "dict[str, dict[str, str]]" is not assignable to type "dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None"
     "dict[str, dict[str, str]]" is not assignable to "dict[Hashable | tuple[Hashable, ...], dict[str, Any]]"
       Type parameter "_KT@dict" is invariant, but "str" is not the same as "Hashable | tuple[Hashable, ...]"
     "dict[str, dict[str, str]]" is not assignable to "None" [reportArgumentType]

疑问:str属于Hashable类型,那list[str]应该符合HashableList[Hashable]的要求,为何会报错?

错误原因与解决方法

1. mosaic参数的类型不匹配问题

HashableList[Hashable]是matplotlib定义的类型别名,本质等价于Sequence[Hashable]。Python泛型中,list是不变类型——也就是说,即便list[str]是Sequence[Hashable]的子类,list[list[str]]也不能直接赋值给list[Sequence[Hashable]],类型检查器要求泛型参数完全一致。

解决方法:
给函数添加明确的类型注解,将内部列表替换为协变的tuple,或者指定返回的mosaic类型为Sequence[Sequence[str]]:

from typing import Sequence, Dict, Hashable, Any

def create_mosaic(num_rows: int) -> tuple[Sequence[Sequence[str]], Dict[Hashable, Dict[str, Any]]]:
    def base_panel(idx: int) -> tuple[str, str, str]:
        return (f"rgb{idx}", f"hist{idx}", f"polar{idx}")

    mosaic: list[Sequence[str]] = []
    per_subplot_kw: Dict[Hashable, Dict[str, Any]] = {}

    for i in range(num_rows):
        mosaic.append(base_panel(i))
        per_subplot_kw[f"polar{i}"] = {"projection": "polar"}
    return mosaic, per_subplot_kw

2. per_subplot_kw的类型不匹配问题

Python的dict泛型是键类型不变的,即便str属于Hashable,dict[str, ...]也不能直接赋值给dict[Hashable | tuple[...], ...]——类型检查器要求键的泛型参数完全匹配,而非子类关系。

解决方法:
给per_subplot_kw添加明确的类型注解,指定键类型为Hashable、值类型为Dict[str, Any](如上例代码所示),让类型检查器识别其符合subplot_mosaic的参数要求。

内容的提问来源于stack exchange,提问作者MaKaNu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 20:13:08