python / python/mypy

Possibly-undefined: allow assertions on the lengths of sequences

Open
#14,830 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-possibly-undefined
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

The new (disabled-by-default) possibly-undefined error code is great, and I'm using it in several of my projects. There are many hits if you enable it for typechecking mypy's own code, however. An example is this function, where mypy (correctly) points out that arg may be undefined on line 526 (arg_types might be an empty list).

https://github.com/python/mypy/blob/456dcbdd6a2f9b36249e0e7d31e521f5678a8235/mypy/suggestions.py#L509-L527

It would be nice if we could use assertions based on the truthiness of a sequence to make this error go away. E.g., it would be nice if we could silence the error here with this diff:

--- a/mypy/suggestions.py
+++ b/mypy/suggestions.py
@@ -512,6 +512,7 @@ class SuggestionEngine:
         arg_names: list[list[str | None]],
         arg_types: list[list[Type]],
     ) -> str:
+        assert arg_types
         args: list[str] = []

Mypy doesn't currently understand this idiom, however. @ilinum, how hard might this kind of thing be to implement?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the example in mypy/suggestions.py around lines 509-527 and reproduce the possibly-undefined warning with the option enabled. Trace the type-checking path for the assert arg_types example; done when this assertion correctly establishes that the sequence is non-empty and removes the warning.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.