Skip to content

Walrus operator + type inference + generic class + some other conditions = mypy failure #9743

Closed
@dnaaun

Description

@dnaaun

Bug Report

from typing import (
    Generic,
    TypeVar,
)
_MyType = TypeVar("_MyType", str, float) 

class MyGeneric(Generic[_MyType]):
    def __init__(self, attr: int) -> None:
        ls = [0]
        self.attr = attr          # mypy says: error: Need type annotation for 'attr'
        if (a := sum(ls)): # mypy says: error: Cannot determine type of 'ls'
            pass
        reveal_type(ls)        # mypy says: note: Revealed type is 'builtins.list[builtins.int*]'

The title of this bug report was a bit vague because I didn't know how to concisely describe the necessary set of conditions for this bug. Here are those conditions:

  1. ls is not manually annotated.
  2. The walrus operator is used.
  3. The block is inside a generic class.
  4. _MyType is a TypeVar that explicitly enumerates all the possible types (as opposed to being bound=... or just a free TypeVar)

Environment
mypy 0.800+dev.40fd841a005936d95e7c351435f1b7b7b4bdd43d
No mypy.ini config, no cmdline flags.
Python 3.8.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-pep-572PEP 572 (walrus operator)

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions