python / python/mypy

[possibly-undefined] Track conditional assignment

Open
#14,310 1 comment 2 reactions 1 assignee View on GitHub

@ilinum is already working on this.

Since Dec 17, 2022.

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

Description

Feature

A common false-positive pattern I've seen for possibly-undefined is separating the conditional assignment and usage. It would be awesome if mypy could track the condition and thus recognize that the usage happens with the same condition.

Not sure if it's possible to implement. Even pyright hasn't done it (yet).

/CC: @ilinum

def some_func() -> bool:
    return True

var = some_func()
other_conditional: bool = True

if var:
    description = "Hallo"

... # some other code, which doesn't modify `var`

if var:  # maybe a bit easier
    print(description)  # Name "description" may be undefined

if var and other_conditional:
    print(description)  # Name "description" may be undefined

This will likely only work for local variables as we can't easily be sure instance attributes aren't changed by the code block in between the definition and usage.

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.