Skip to content

Literal broadened to superclass erroneously #12215

Closed

Description

@adamjstewart

Bug Report

In some situations, the type checker will broaden a Literal to its superclass, causing type errors.

To Reproduce

Create the following test.py file:

from typing import *

def foo() -> Iterable[Union[Tuple[Literal["foo"], int], Tuple[Literal["bar"], str]]]:
    for i in range(10):
        if i % 2 == 0:
            yield "foo", i
        else:
            yield "bar", str(i)

Expected Behavior

I would expect these type hints to be correct.

Actual Behavior

$ mypy test.py 
test.py:7: error: Incompatible types in "yield" (actual type "Tuple[str, int]", expected type "Union[Tuple[Literal['foo'], int], Tuple[Literal['bar'], str]]")
test.py:9: error: Incompatible types in "yield" (actual type "Tuple[str, str]", expected type "Union[Tuple[Literal['foo'], int], Tuple[Literal['bar'], str]]")
Found 2 errors in 1 file (checked 1 source file)

Here, "actual type" should not be Tuple[str, int] or Tuple[str, str], it should be Tuple[Literal['foo'], int] or Tuple[Literal['bar'], str].

Your Environment

  • Mypy version used: 0.920
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.9.9
  • Operating system and version: macOS 10.15.7

Activity

  1. anentropic commented on Apr 25, 2022

    @anentropic

    Another example of similar behaviour:

    from typing import Any, Literal, TypeVar
    
    
    T = TypeVar('T', bound=Any)
    
    
    def original() -> Literal["a", "b", "c"] | None:
        return "a"
    
    
    def get_some(val: T | None) -> T:
        assert val is not None
        return val
    
    
    val = get_some(original())
    reveal_type(val)

    Gives:

    demo2.py:17: note: Revealed type is "builtins.str*"
    

    ...the "literal-ness" of T got lost in the process of narrowing the type from Optional[T] to T.

  2. erictraut commented on Aug 13, 2023

    @erictraut

    This appears to have been fixed in mypy 0.93. I think it can be closed.

  3. hauntsaninja commented on Aug 13, 2023

    @hauntsaninja
    Collaborator

    Fixed in #11236

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions