microsoft / pyright

Static Type Checker for Python
Other
12.7k stars 1.35k forks source link

Unpacking of iterables with unknown/wrong length #8290

Closed not-my-profile closed 2 weeks ago

not-my-profile commented 2 weeks ago

It would be nice if Pyright could have a diagnostic rule to detect e.g. the following:

def foo(x: list[int]):
    a, b = x

which will fail with a ValueError if there aren't enough or too many values to unpack.

This would encourage developers to use tuple types in parameters when a specific length is required.

Pyright currently also doesn't detect wrong unpacking of literals e.g:

a, b = "abc"

Mypy detects this by forbidding string unpacking in general (Unpacking a string is disallowed), which does however mean mypy flags a, b = "ab" as a false positive.

Especially when iterating over iterables of union types this type checking would be helpful, e.g Pyright currently doesn't flag the problem in:

def foo(x: list[tuple[int, int] | Literal["foo"]):
    for a, b in x:
        pass
erictraut commented 2 weeks ago

I'm reluctant to add a diagnostic rule for something that is neither a type error and is completely legitimate and correct code. That goes against the principles that we've used consistently within pyright. It would be possible to make this a separate diagnostic check, but such a check would need to be completely optional — not even enabled in "strict" type checking mode. Such checks are rarely used because they're difficult to discover, so we tend not to add such checks.

I'm going to reject this enhancement request for now, but I'm willing to revisit it again if there's a strong signal from other pyright users (e.g. in the form of thumbs-up reactions to this issue).