Skip to content

slice behavior difference in mypy 1.14+dev and 1.13 #18225

Closed
@Dr-Irv

Description

@Dr-Irv

We test pandas-stubs with the nightly version of mypy. It reveals an issue with how a method that returns slice is annotated. With pandas-stubs, we get an error like this with the development version of mypy:

tests/test_frame.py:2401: error: Expression is of type "tuple[Index[int], slice[None, None, None]]", not "tuple[Index[int], slice[Any, Any, Any]]"  [assert-type]

In this case, the assert_type() call of assert_type(pd.IndexSlice[ind, :], tuple["pd.Index[int]", slice]) works with mypy 1.13, fails with the 1.14 dev version.

This is due to a change in typeshed where slice has become generic. I think that change in typeshed is bundled with the 1.14+dev version of mypy, not the released version 1.13.

A simpler example is below. Not sure if this is a mypy or a typeshed issue.

Bug Report

mypy 1.14+dev infers a different value for slice than 1.13

To Reproduce
Requires 2 files.

First, there is retslice.pyi:

from typing import TypeAlias, TypeVar

class Index:
    ...

_IndexSliceTuple: TypeAlias = tuple[
    Index | int | float | str | slice , ...
]

_IndexSliceUnion: TypeAlias = slice | _IndexSliceTuple

_IndexSliceUnionT = TypeVar("_IndexSliceUnionT", bound=_IndexSliceUnion)

class _IndexSlice:
    def __getitem__(self, arg: _IndexSliceUnionT) -> _IndexSliceUnionT: ...

IndexSlice: _IndexSlice

Then there is mypyslice.py :

from typing import assert_type
from retslice import IndexSlice, Index

foo = IndexSlice[Index(), :]
assert_type(foo, tuple[Index, slice])

Expected Behavior

No errors reported by mypy 1.14+dev

Actual Behavior

mypyslice.py:5: error: Expression is of type "tuple[Index, slice[None, None, None]]", not "tuple[Index, slice[Any, Any, Any]]"  [assert-type]

Your Environment

  • Mypy version used: v1.14.0%2Bdev.9405bfd9205ea369c11150907764fa46c03cb1f7
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.13

May be related to #18149

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions