letsBeePolite
letsBeePolite

Reputation: 2251

Incompatible types in assignment while type hinting Python3

For a simple py code when I am using the type it throws me the following error:
error: Incompatible types in assignment (expression has type "object", variable has type "List[str]")

I have tried replacing List[str] with List[AnyStr] but still it doesnt helps.

The following is the skeleton of the 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]}")
   

Upvotes: 1

Views: 2107

Answers (1)

chepner
chepner

Reputation: 531345

You declared, in the type signature, that Y will be a list of strings. The whole point of using mypy is to stop you from assigning something other than a list of strings (like a range object) to Y later in the function.

The solution is simple: convert the range object to a list of strings immediately, rather than waiting until later.

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])

Upvotes: 3

Related Questions