python / python/mypy

`super().__new__` inherited from Tuple doesn't match element type

Open
#8,541 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

needs discussion priority-1-normal
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Hi, when I inherit from Tuple[float, float, float], and pass a tuple of floats as an argument to super().__new__, I get an error saying that an Iterable[_T_co] was expected instead. As per the typeshed stub, _T_co is supposed to be the type of the tuple elements, so I guess it's not getting deduced correctly. Further, this works with tuple.__new__, so the involvement of super() must be to blame and the type signatures indeed aren't identical.

from typing import Tuple, Type, TypeVar

CoordsT = TypeVar('CoordsT', bound='Coords')
class Coords(Tuple[float, float, float]):
    def __new__(cls: Type[CoordsT]) -> CoordsT:

        reveal_type(super().__new__)
        # Revealed type is 'def [_T] (cls: Type[_T`-1], iterable: typing.Iterable[_T_co`1] =) -> _T`-1'
        reveal_type(tuple.__new__)
        # Revealed type is 'def [_T_co, _T] (cls: Type[_T`-1], iterable: typing.Iterable[_T_co`1] =) -> _T`-1'

        value = (0.0, 0.0, 0.0)
        result = tuple.__new__(cls, value)
        # fine
        super().__new__(cls, value)
        # error: Argument 2 to "__new__" of "tuple" has incompatible type "Tuple[float, float, float]"; expected "Iterable[_T_co]"

        return result

I'm not sure if it's mypy or typeshed that is responsible for the function signature of super's __new__, but I didn't find an overload for it in typeshed, so I suspect this is mypy's remit

Edit: mypy 0.770, Python 3.7.3

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 with the reproducer and compare the revealed types for super().__new__ and tuple.__new__. Inspect the referenced typeshed builtins.pyi signature, then trace how mypy handles the inherited __new__ call. Done means the shown super().__new__(cls, value) call accepts the tuple of floats without the reported type error.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.