SciPy Type Stubs

1.17.1.3 · active · verified Fri Apr 10

scipy-stubs provides comprehensive type annotations for the SciPy library, enabling static type checking for SciPy-based projects and enhancing IDE features like autocompletion and error detection. It offers full coverage of the public SciPy API with precise shape-typing and dtype-typing without any runtime overhead. The current version is 1.17.1.3, designed to be compatible with SciPy 1.17.1 and supporting Python 3.11-3.14. Releases are independent but target specific SciPy versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using `scipy.optimize.minimize` with type annotations for inputs and outputs. After installing `scipy-stubs`, your type checker (like MyPy or Pyright) and IDE will automatically provide type-checking and autocompletion for SciPy functions, even without explicit type annotations in your own code. The stubs ensure that the types for `x0`, `res`, and function arguments are correctly understood.

import numpy as np
from scipy.optimize import minimize, OptimizeResult
from typing import Tuple

def rosen(x: np.ndarray) -> np.float64:
    """The Rosenbrock function"""
    return np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)

def rosen_der(x: np.ndarray) -> np.ndarray:
    """The Rosenbrock function gradient"""
    xm = x[1:-1]
    xm_m1 = x[:-2]
    xm_p1 = x[2:]
    grad = np.zeros_like(x)
    grad[1:-1] = 200.0 * (xm - xm_m1**2) - 400.0 * (xm_p1 - xm**2) * xm - 2.0 * (1 - xm)
    grad[0] = -400.0 * x[0] * (x[1] - x[0]**2) - 2.0 * (1 - x[0])
    grad[-1] = 200.0 * (x[-1] - x[-2]**2)
    return grad

x0: np.ndarray = np.array([0.5, 0.5])
res: OptimizeResult = minimize(rosen, x0, method='BFGS', jac=rosen_der, options={'disp': True})

print(f"Optimization successful: {res.success}")
print(f"Function value at minimum: {res.fun}")
print(f"Optimal parameters: {res.x}")

view raw JSON →