microsoft / pyright

Static Type Checker for Python
Other
13.03k stars 1.39k forks source link

Support Literal Interference from Exponentiation #8434

Closed max-muoto closed 1 month ago

max-muoto commented 1 month ago

Similar to https://github.com/microsoft/pyright/issues/8419, it would also be helpful to support exponentiation:

from typing import reveal_type, Final

MY_CONST: Final = 2**2

reveal_type(MY_CONST) # revealed type is `int`

We can also end up with Any once we reach 2^26 for whatever reason (separate from this, I feel this could lead to subtle bugs):

LARGE_NUM: Final = 2**32 - 1

reveal_type(LARGE_NUM) # revealed type is `Any`.

Playground Link

MyPy handles both cases correctly, revealing Literal[4], and Literal[4294967295], so support in Pyright would be nice. At least for me, it's not uncommon to keep constants created through exponentiation, especially when dealing with byte units.

erictraut commented 1 month ago

The rules for exponentiation are a bit subtle in python, so I had good reason not to include this operator in pyright's initial implementation of "literal math". I think there are ways we could make this work within some limitations.

I'll note that mypy appears to have a bug where it doesn't apply appropriate limitations and crashes. MY_CONST: Final = 2**100000. I'll file a bug on this issue.

erictraut commented 1 month ago

This will be included in the next release.

max-muoto commented 1 month ago

This will be included in the next release.

Thanks Eric, super helpful

erictraut commented 1 month ago

This is included in pyright 1.1.372.