python / python/mypy

@overload declarations in stubs - required to be directly adjacent?

Open
#10,120 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

Currently, mypy requires @overload declarations in stubs to be directly adjacent, with no declarations (e.g. type vars) in between. However, I don't find that requirement in PEP 484 [1], nor in the typing module documentation [2].

[1] https://www.python.org/dev/peps/pep-0484/#function-method-overloading
[2] https://docs.python.org/3/library/typing.html#typing.overload

To Reproduce
Consider the following type stub:

import typing

@typing.overload
def foo() -> None: ...

K = typing.TypeVar('K')
@typing.overload
def foo(k: K) -> K: ...

Then run stubtest on it.

Expected Behavior
According to the documentation, I would expect this stub to be valid.

Actual Behavior

$ python -m mypy.stubtest teststub
error: failed mypy build.
teststub.pyi:4: error: Single overload definition, multiple required
teststub.pyi:8: error: Name 'foo' already defined on line 4
teststub.pyi:8: error: Single overload definition, multiple required

Pulling the type var declaration up fixes it:

import typing

K = typing.TypeVar('K')

@typing.overload
def foo() -> None: ...

@typing.overload
def foo(k: K) -> K: ...

Your Environment
Python 3.7.1 (anaconda) on Linux, latest master of mypy.
I also tested with mypy 0.790 on Windows, with the same result.

$ python --version
Python 3.7.1
$ python -m mypy --version
mypy 0.820+dev.497556f466dcda90d850b23e86c55ec4082be3f5

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

Start by reproducing the failure with the shown teststub and python -m mypy.stubtest teststub. Trace how mypy validates adjacent @typing.overload declarations and add a regression test covering the intervening TypeVar; done means the stub is accepted while existing overload diagnostics remain correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.