Skip to content

Literal types are widened for not-annotated instance variables #3256

Description

@twoertwein

Describe the bug
When assigning a Literal-annotated variable as an not-annotated instance variable, pyright widens the literal type but only when the variable is accessed in a different method.

To Reproduce

# pyright: strict
from typing import Literal

SomeOption = Literal["a", "b", "c"]

def foo(x: SomeOption):
    ...

class Test:
    def __init__(self, x: SomeOption):
        self.x = x
        foo(self.x)  # passes

    def test(self):
        foo(self.x)  # errors

error: Argument of type "str" cannot be assigned to parameter "x" of type "SomeOption" in function "foo"
  Type "str" cannot be assigned to type "SomeOption"
    "str" cannot be assigned to type "Literal['a']"
    "str" cannot be assigned to type "Literal['b']"
    "str" cannot be assigned to type "Literal['c']" (reportGeneralTypeIssues)

with pyright 1.1.232

Metadata

Metadata

Assignees

No one assigned

    Labels

    as designedNot a bug, working as intended

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions