PyTorch PR #193421 enables strict pyrefly on numpy ndarray wrapper
Strict pyrefly checking lands on torch/_numpy/_ndarray.py with zero new errors
PyTorch's PR #193421, authored by aorenste with Claude, marks a step forward in type safety for the popular deep learning framework. The change removes the blanket `# mypy: ignore-errors` directive from torch/_numpy/_ndarray.py and instead enables strict pyrefly checking via a per-file sub-config. This file implements the NumPy-compatible `ndarray` wrapper over `torch.Tensor`, meaning improved static checking here directly impacts users who rely on PyTorch's NumPy interoperability. The PR successfully avoids introducing any net-new pyrefly errors, holding the count at 156 both before and after the change.
The work involves careful annotation and handling of PyTorch's dynamic method creation. Many of ndarray's methods and operators, along with the `_funcs` and `_ufuncs` members they reference, are generated at runtime through `vars()[name] = ...` loops, making them invisible to static analysis. Those references now carry targeted `# pyrefly: ignore` comments for missing attributes, documented at each use site. Additionally, `__eq__`, `__ne__`, and `__repr__` intentionally deviate from object signatures to match NumPy semantics, so bad-override warnings are suppressed with explanatory comments. The `resize` method was reworked so its shape normalization is type-clean while preserving behavior: it accepts a single tuple/list arg or int varargs, raises TypeError for non-integer dims, and ValueError for negative dims, matching NumPy and existing tests. With tests passing (pytest on test/torch_np), a clean lintrun, and approval from Skylion007, this PR demonstrates how strict type checking can be adopted pragmatically even in a large, dynamic codebase.
- Removes blanket `# mypy: ignore-errors` from torch/_numpy/_ndarray.py and enables strict pyrefly via per-file sub-config
- No net-new pyrefly errors: 156 errors before and after the PR, using targeted `# pyrefly: ignore` comments for dynamic methods
- Reworks `resize` for type-clean shape normalization (tuple/list or int varargs, TypeError/ValueError for invalid dims) — behavior unchanged per tests
Why It Matters
Stricter type checking in PyTorch's NumPy compatibility layer reduces bugs and improves maintainability for millions of developers.