python - 类型提示 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]}")
解决方案
您在类型签名中声明这Y
将是一个字符串列表。使用的全部mypy
目的是阻止您将字符串列表(如对象)以外的其他内容分配给函数的稍后部分。range
Y
解决方案很简单: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])
推荐阅读
- r - 如何在 R 中写出这个总和?
- javascript - 为什么我的返回 row[0] === userId.matches(userId); 什么都不显示?
- wso2 - 使用 Oauth2 和 SOAP 创建服务提供者
- discord.js - 使用 .then() 向 1 个频道发送 2 条消息
- python - 如何在 Python 中的某个起点将某些十六进制值放入数组中
- discord - 检查消息是否有 7 个字母,然后发送到频道
- python - 使用 genfromtxt() 和转换器导入 csv
- c# - 没有按钮的弹出窗口 Xamarin.Forms
- c++ - Azure Function 项目在本地构建和部署,但不是来自 azure dev ops 管道
- c - 是否从 C 标准定义的同一联合中的不同成员分配给联合成员?