python / python/mypy

Incorrect inferred type for attribute with two partial types

Open
#20,257 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Unexpected type is inferred for attribute x in this example:

class C:
    def __init__(self) -> None:
        if int():
            self.x = None
            return
        self.x = []
        self.x.append("x")

reveal_type(C().x)  # "list[str]" -- but should be "list[str] | None"

The inferred type should be list[str] | None, or alternatively mypy could require a type annotation for x, if this is too tricky to infer.

This should be tested with and without --allow-redefinition-new, since it may make a difference.

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 reproducing the provided class C example in mypy, checking the revealed type with and without --allow-redefinition-new. Trace the inference behavior for the two assignments to x and add a regression test covering both modes; done means mypy reports list[str] | None or consistently requires an annotation.

Written by the indexing model from the issue text.

Assessment

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