Skip to content

[red-knot] Detect unreachable attributes assignments #15967

@sharkdp

Description

@sharkdp

This is probably not a high-priority feature, but it would be great if we could detect attribute assignments in unreachable code sections, and eliminate them from the set of possible answers:

class C:
    def __init__(self) -> None:
        if True:
            self.x = 1
        else:
            self.x = "a"

        return

        self.y = "unreachable"

reveal_type(C().x)  # should be `Unknown | Literal[1]` (i.e. not include `Literal["a"]`)

# Should be an error:
C().y

Note that we have one existing test for this here:

```py
class C:
def __init__(self) -> None:
# We use a "significantly complex" condition here (instead of just `False`)
# for a proper comparison with mypy and pyright, which distinguish between
# conditions that can be resolved from a simple pattern matching and those
# that need proper type inference.
if (2 + 3) < 4:
self.x: str = "a"
# TODO: Ideally, this would result in a `unresolved-attribute` error. But mypy and pyright
# do not support this either (for conditions that can only be resolved to `False` in type
# inference), so it does not seem to be particularly important.
reveal_type(C().x) # revealed: str
```

Metadata

Metadata

Assignees

No one assigned

    Labels

    tyMulti-file analysis & type inference

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions