Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
elprans opened this issue Dec 17, 2021 · 3 comments
Closed
Labels
bug mypy got something wrong

Comments

@elprans
Copy link
Contributor

elprans commented Dec 17, 2021

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']

@elprans elprans added the bug mypy got something wrong label Dec 17, 2021
@pranavrajpal
Copy link
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.

@hauntsaninja
Copy link
Collaborator

hauntsaninja commented Dec 18, 2021

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

@elprans
Copy link
Contributor Author

elprans commented Dec 18, 2021

@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!

@elprans elprans closed this as completed Dec 18, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants