python / python/mypy

scipy-stubs: `scipy.optimize.least_squares` function inferred as module

Open
#20,079 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

As reported in https://github.com/scipy/scipy-stubs/issues/939, mypy seems to infer scipy.optimize.least_squares as a ModuleType. Other type-checkers (pyright, basedpyright, pyrefly) correctly infer it as a function.

from typing import reveal_type
from scipy.optimize import least_squares

reveal_type(least_squares)
  • mypy: Revealed type is "types.ModuleType"
  • pyrefly: revealed type: (fun: (🍝) -> OptimizeResult
  • (based)pyright: Type of "least_squares" is "(fun: (🍝) -> OptimizeResult"

(🍝 = the huge function signature)

This seems to occur on (at least) scipy-stubs 1.16.2.0 and 1.16.2.3, using mypy 1.18.2.

To repro, install scipy-stubs[scipy]==1.16.2.3 (currently the latest) from pypi or scipy-typed from conda.

Here's are the relevant bits of code:

  1. optimize/__init__.pyi re-exports from ._lsq import least_squares through __all__
  2. optimize/_lsq/__init__.pyi re-exports from .least_squares import least_squares through __all__
  3. optimize/_lsq/least_squares.pyi contains the definition for the least_squares function

It looks like mypy ignores step optimize/_lsq/__init__.pyi from 2., causing it to resolve the optimize._lsq.least_squares module, instead of (explicitly re-exported) optimize._lsq.least_squares.least_squares function.

I expect to be able to work around this by changing from ._lsq import least_squares in optimize/__init__.pyi to from ._lsq.least_squares import least_squares.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the report with scipy-stubs[scipy]==1.16.2.3 and mypy 1.18.2, using the reveal_type example. Compare optimize/init.pyi, optimize/_lsq/init.pyi, and optimize/_lsq/least_squares.pyi, then verify that importing scipy.optimize.least_squares reveals the function rather than ModuleType.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.