python / python/mypy

Possible regression: incorrectly ret type detected in of __new__

Open
#11,835 2 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

Bug Report

new versions of mypy seem to misinterpret the return type of the __new__ method defined below

To Reproduce

# t.py
class A:
    def __new__(cls, *args, **kwargs) -> "B | C":
        if cls is A:
            cls = B
        else:
            cls = C
        return object.__new__(cls)

class B(A):
    pass

class C(A):
    pass

checking this file gives

$ mypy t.py
t_typ.py:2: error: "__new__" must return a class instance (got "Union[B, C]")
t_typ.py:7: error: Incompatible return value type (got "A", expected "Union[B, C]")
Found 2 errors in 1 file (checked 1 source file)

The first error is not new and was already discussed in https://github.com/python/mypy/issues/1020, I'm okay with it being marked as "won't fix" even though my opinion diverges.
The second error however (error: Incompatible return value type (got "A", expected "Union[B, C]")) appeared at some point after mypy 0.910 and mypy 0.920, and I believe that it is not correct.
Indeed the return type of the method is detected as A, but it is guarded against by the if/else clause above.

For reference, a pattern similar to the one I'm usin described can be found in CPython's standard library, in pathlib.Path.__new__:

    def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        self = cls._from_parts(args)
        if not self._flavour.is_supported:
            raise NotImplementedError("cannot instantiate %r on your system"
                                      % (cls.__name__,))
        return self

Expected Behavior
Only the first error should show up. None at all would be ideal in my opinion, but that seems out of line here.

Your Environment

  • Mypy version used: 0.910 and 0.930
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10.0
  • Operating system and version: MacOS 12.0.1

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 running the reproduced example in t.py with the documented mypy versions and compare the two diagnostics for new. Read the analogous pathlib.Path.new pattern and trace the return-type analysis for the guarded cls branches; done means the incompatible return-value error no longer appears while the existing first diagnostic remains unchanged.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.