python / python/mypy

@overload using `Sequence[Never]` to match empty sequence

Open
#15,763 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Apologies if this is a duplicate.

Bug Report

Sequence[Never] should match Sequence[<nothing>] in order to allow specifying overloads for empty sequences.

To Reproduce

The following code raises no errors when using pyright:

from typing import Generic, TypeVar, Any, Sequence, overload

from typing_extensions import Never, assert_type

T = TypeVar("T")

float_t = TypeVar("float_t", bound=float)
int_t = TypeVar("int_t", bound=int)

# NOTE: for type hints: int ≤ float ≤ complex


class Vec(Generic[T]):
    # @overload
    # def __new__(cls, data: Any, dtype: type[int_t]) -> "Vec[int_t]": ...

    @overload
    def __new__(cls, data: Any, dtype: type[float_t]) -> "Vec[float_t]": ...

    @overload
    def __new__(cls, data: Sequence[Never], dtype: None = ...) -> "Vec": ...

    @overload
    def __new__(cls, data: Sequence[T], dtype: None = ...) -> "Vec[T]": ...

    def __new__(cls, *args, **kwargs) -> "Vec":
        return super().__new__(cls)

    def __init__(self, data, dtype=None):
        self.data = data
        self.dtype = dtype


assert_type(Vec([]), "Vec[Any]")                        # Vec[<nothing>], not Vec[Any]
assert_type(Vec([], dtype=int), "Vec[int]")             # Vec[<nothing>], not Vec[int]
assert_type(Vec([], dtype=float), "Vec[float]")         # Vec[<nothing>], not Vec[float]
assert_type(Vec([1, 2, 3]), "Vec[int]")                 # Vec[<nothing>], not Vec[int]
assert_type(Vec([1, 2, 3], dtype=float), "Vec[float]")  # Vec[<nothing>], not Vec[float]
assert_type(Vec([1.2345]), "Vec[float]")                # Vec[<nothing>], not Vec[float]

https://mypy-play.net/?mypy=master&python=3.11&gist=0866fc1909bf0993c8e42e20ac70a997

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

The issue provides a Python overload reproduction and a mypy-play link, but names no repository files or tests. Start by running the example against mypy and compare inference for empty and non-empty sequences; done means the stated assert_type expectations pass without regressing the other overload cases.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.