首页 > 解决方案 > 类型提示 Python3 时分配中的类型不兼容

问题描述

对于一个简单的 py 代码,当我使用该类型时,它会抛出以下错误:
error: Incompatible types in assignment (expression has type "object", variable has type "List[str]")

我尝试过替换List[str]List[AnyStr]但仍然没有帮助。

以下是func的骨架:

import uuid
from typing import List
import numpy as np
def plot_X(
    X: List[np.array],
    Y: List[str], ### Line throwing error
    name: str = str(uuid.uuid4()),
    xlabel: str = "Values",
    ylabel: str = "Likelihood",
    title: str = "Title",
    X_to_plot: int = 10, 
    show=False,
) -> None:

    Y = Y if Y else range(len(X))
    if len(X) > X_to_plot:
        idxs = np.random.randint(0, len(X), X_to_plot, replace=False)
        X = X[idxs]
        Y = Y[idxs] if Y else range(X_to_plot)

    X = X[:X_to_plot]
    Y = Y[:X_to_plot]

    fig, ax = plt.subplots(figsize=(14, 12))

    for i in range(len(X)):
        ax.plot(X[i], linewidth=1.5, label=f"{Y[i]}")
   

标签: pythontype-hinting

解决方案


您在类型签名中声明这Y将是一个字符串列表。使用的全部mypy目的是阻止您将字符串列表(如对象)以外的其他内容分配给函数的稍后部分。rangeY

解决方案很简单:range立即将对象转换为字符串列表,而不是等到以后。

def plot_X(
    X: List[np.array],
    Y: List[str],
    name: str = str(uuid.uuid4()),
    xlabel: str = "Values",
    ylabel: str = "Likelihood",
    title: str = "Title",
    X_to_plot: int = 10, 
    show=False,
) -> None:

    if not Y:
        Y = [str(x) for x in range(len(X))]
 
    if len(X) > X_to_plot:
        idxs = np.random.randint(0, len(X), X_to_plot, replace=False)
        X = X[idxs]
        if Y:
            # Based on the use of Y in ax.plot, I'm
            # assuming that Y[idxs] may not be a list
            # of strings.
            Y = [str(y) for y in Y[idxs]]
        else:
            Y = [str(x) for x in range(len(X))]

    X = X[:X_to_plot]
    Y = Y[:X_to_plot]

    fig, ax = plt.subplots(figsize=(14, 12))

    for i in range(len(X)):
        ax.plot(X[i], linewidth=1.5, label=Y[i])

推荐阅读