ty icon indicating copy to clipboard operation
ty copied to clipboard

Narrowing to Any/Unknown loses type information

Open Decodetalkers opened this issue 3 weeks ago • 2 comments

Summary

import numpy as np
import matplotlib.pyplot as plt
from model import Perception

data = np.genfromtxt("perceptron_toydata.txt", delimiter="\t")
X: np.ndarray
Y: np.ndarray
X, Y = data[:, :2], data[:, 2]
Y = Y.astype(np.int64)

print("Class label counts:", np.bincount(Y))
print("X.shape:", X.shape)
print("y.shape:", Y.shape)

shuffle_idx = np.arange(Y.shape[0])
shuffle_rng = np.random.RandomState(123)
shuffle_rng.shuffle(shuffle_idx)
X = X[shuffle_idx]
Y = Y[shuffle_idx]

X_train: np.ndarray
X_test: np.ndarray
Y_train: np.ndarray
Y_test: np.ndarray

X_train, X_test = X[shuffle_idx[:70]], X[shuffle_idx[70:]]
Y_train, Y_test = Y[shuffle_idx[:70]], Y[shuffle_idx[70:]]

So I have already mark the X_train is np.ndarray, but the type hint did not work

Image

Version

ty 0.0.7

Decodetalkers avatar Dec 26 '25 15:12 Decodetalkers

Thanks for the report! I'll transfer this to the ty repo.

I think this might be related to https://github.com/astral-sh/ty/issues/136, but someone else will probably have a better answer than I do :)

ntBre avatar Dec 26 '25 16:12 ntBre

This is definitely closely related to #136, but I'll keep it open as a separate sub-issue; the plan in #136 is to prefer the annotation over the inferred type in an annotated assignment, but that actually wouldn't help in this case. In this case we either want to avoid "narrowing" to Any / Unknown at all, or we want to narrow to the intersection (ndarray & Unknown).

carljm avatar Dec 26 '25 16:12 carljm