Skip to content

0.920 Regression: literal unions aren't inferred from conditionals anymore #11782

Closed

Description

@elprans

test.py:

def foo(h: bytes) -> int:
    if h[5] == 2:
        byteorder = "big"
    elif h[5] == 1:
        byteorder = "little"
    else:
        raise AssertionError(
            f"unexpected ELF endianness: {h[5]}"
        )
    return int.from_bytes(h[16:18], byteorder=byteorder, signed=False)

Results in

$ mypy test.py
1.py:10:17: note: Revealed type is "builtins.str"
1.py:11:47: error: Argument "byteorder" to "from_bytes" of "int" has incompatible type "str"; expected "Union[Literal['little'], Literal['big']]"

With mypy-0.920 and later. 0.910 correctly inferred byteorder as Literal['little'] | Literal['big']

Activity

  1. pranavrajpal commented on Dec 18, 2021

    @pranavrajpal
    Contributor

    I don't think mypy ever inferred the type of byteorder as Literal['little', 'big']. I think we always inferred str but 0.920 changed the type signature of int.from_bytes to take a Literal instead of a str, turning this into an error. (That change was added in python/typeshed#5715 and added to mypy in #10862, which was included in 0.920).

    You can silence the error by adding an explicit Literal["little", "big"] type for byteorder.

  2. hauntsaninja commented on Dec 18, 2021

    @hauntsaninja
    Collaborator

    TBH I find several of these typeshed Literal changes to be quite problematic, e.g. here's one I recently reverted python/typeshed#6566

  3. elprans commented on Dec 18, 2021

    @elprans
    ContributorAuthor

    @pranavrajpal, you're right, 0.910 also doesn't infer byteorder as Literal. I somehow convinced myself that it did. Not an inference regression then. Thanks for the explanation!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions