python / python/mypy

Regression: false positive avoid redundant cast with literal union

Open
#19,055 6 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

This example started generating an error after #18588, which looks like a regression:

# mypy: warn-redundant-casts

from typing import Literal, cast

Foo = Literal["a", "b"]

class C:
    def __init__(self) -> None:
        self.x = cast(Foo, "a")  # error: Redundant cast to "Literal['a', 'b']"

I haven't looked into this in detail, but it seems possible that we infer a union type for "a" in a literal union context, which doesn't look right. If this is a correct hypothesis, #18588 wouldn't actually be the root cause, and it would just be exposing a pre-existing issue.

cc @asottile as the author of the PR

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 example in issue #19055 with mypy's warn-redundant-casts setting, then inspect the behavior introduced by #18588 and the literal-union inference path. Done means the cast in the example is no longer reported as redundant, with a regression test covering this case.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.