python / python/mypy

Incorrectly inferred type for expression

Open
#17,561 0 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

The type for super().__new__(cls, value) is incorrectly inferred when used outside of __new__.

In the example below I used super().__new__(cls, value) in __init_subclass__ and the inferred type is the base class that defines __init_subclass__ instead of being Self. At the same time within __new__, the same expression is correctly inferred as Self.

To Reproduce

from typing import ClassVar, Self, reveal_type

class LiteralBytes(bytes):
    _instance_: ClassVar[Self] = NotImplemented

    def __init_subclass__(cls, *, value: bytes = NotImplemented, **kw: object) -> None:
        if value is not NotImplemented:
            cls._instance_ = reveal_type(super().__new__(cls, value))
        super().__init_subclass__(**kw)

    def __new__(cls) -> Self:
        reveal_type(super().__new__(cls, b''))  # this is here just to showcase the difference in the inferred type
        if cls._instance_ is NotImplemented:
            raise TypeError(f'Cannot instantiate abstract literal bytes type {cls.__qualname__!r} that does not define its value')
        return cls._instance_

The sample program above is also available here: playground link

Expected Behavior

I expect super().__new__(cls, ...) to always be inferred as Self no matter in which method is called as that expression always produces an instance of cls (as long as cls points to the class, i.e. we are in a class method, inside __new__, ...)

Actual Behavior

main.py:8: error: Incompatible types in assignment (expression has type "LiteralBytes", variable has type "Self")  [assignment]
main.py:8: note: Revealed type is "__main__.LiteralBytes"
main.py:12: note: Revealed type is "Self`0"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.12.0+dev.6aa46f097cf30f3143c5ee4bae7f0d2e7ce914bc (compiled: no)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files):
[tool.mypy]
enable_incomplete_feature = "NewGenericSyntax"
disable_bytearray_promotion = true
disable_memoryview_promotion = true
check_untyped_defs = true
warn_unreachable = true
warn_redundant_casts = true
warn_unused_ignores = true
  • Python version used: 3.12

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 in main.py and trace how the type checker infers super().new(cls, value) outside new. Compare that path with the inference inside new. Done means the expression is revealed as Self in both locations and the instance assignment no longer reports an incompatibility.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.