microsoft / pyright

Static Type Checker for Python
Other
13.14k stars 1.4k forks source link

Unclear error message when assigning optional union to non optional union type #8943

Closed LordAro closed 20 hours ago

LordAro commented 1 week ago

Describe the bug

When attempting to assign an optional union type to the same (non optional) union type, the output from pyright is a very unclear Cannot assign to attribute "a" for class Foo* with no other information.

The error message gets clearer with an additional diagnostic message if I remove the union (second code example), though the cannot assign to ... Outer* stuff still feels unclear to me.

Just to clarify, I'm not debating there's an issue here, just that the error message is unclear and does not help me resolve anything :)

Code or Screenshots

import typing

UnionClass = typing.Union['Foo', 'Bar']

class Foo:
    def __init__(self, parent: UnionClass | None):
        self.parent = parent

class Bar:
    def __init__(self, parent: UnionClass | None):
        self.parent = parent

class Outer:
    def __init__(self, a):
        self.a: UnionClass = a

    def pump(self):
        while self.a:
            self.a= self.a.parent  # Error here
/.../test.py
  /.../test.py:22:18 - error: Cannot assign to attribute "a" for class "Outer*" (reportAttributeAccessIssue)
  /.../test.py:22:24 - error: Cannot assign to attribute "a" for class "Outer*" (reportAttributeAccessIssue)
2 errors, 0 warnings, 0 informations
class Foo:
    def __init__(self, parent: 'Foo | None'):
        self.parent = parent

class Outer:
    def __init__(self, a):
        self.a: Foo = a

    def pump(self):
        while self.a:
            self.a= self.a.parent  # Error here
/.../test.py
  /.../test.py:12:18 - error: Cannot assign to attribute "a" for class "Outer*"
    Type "Foo | None" is not assignable to type "Foo"
      "None" is not assignable to "Foo" (reportAttributeAccessIssue)
  /.../test.py:12:24 - error: Cannot assign to attribute "a" for class "Outer*"
    Type "Foo | None" is not assignable to type "Foo"
      "None" is not assignable to "Foo" (reportAttributeAccessIssue)
2 errors, 0 warnings, 0 informations

VS Code extension or command-line Command line. 1.1.379

Abderrahma77524 commented 1 week ago

Once the code has finished running, you might see the cursor reappear or the output continue in the terminal.

If you're seeing this output and the code doesn't appear to be progressing, it's possible that:

The code has gotten stuck in an infinite loop. The code is waiting for an event that's not happening. There's a bug in your code that's preventing it from completing. You'll need to investigate the code further to determine why the cursor is hidden and why the code is not finishing.

LordAro commented 1 week ago

Well that's pretty clearly some AI nonsense. Shoo.

erictraut commented 20 hours ago

This is addressed in pyright 1.1.381.