microsoft / pyright

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

When a class is wrapped with a decorator that adds attributes to the class, the added attributes are not recognized by the language server #8814

Closed ytxmobile98 closed 3 weeks ago

ytxmobile98 commented 3 weeks ago

Environment data

Code Snippet

I recently ran into this issue when I needed to use a class decorator to add custom attributes (methods and properties) to it. As seen below, when I added a decorator (wrap) along the class Foo, it adds a class method bar and a data attribute one to it. But when I then reference these two added attributes, the editor shows red squiggles underneath, and jumping to the initial definitions in the decoration function or auto-completing these attributes are also not possible. Here is a minimal example to reproduce it:

def wrap(cls):
    @classmethod
    def bar(cls):
        print(cls.__name__)

    cls.bar = bar
    cls.one = 1

    return cls

@wrap
class Foo:
    @staticmethod
    def foo():
        print('foo')

def main():
    Foo.foo()
    Foo.bar()
    print(Foo.one)

    print(Foo.__dict__)

if __name__ == '__main__':
    main()

Repro Steps

  1. Write the code above in VSCode
  2. Save it as main.py
  3. See how it marks errors

Expected behavior

The references to bar and one should work normally, i.e. the language server should recognize them as corresponding to what I defined above.

Actual behavior

The language server sees them as unknown attributes.

image

erictraut commented 3 weeks ago

Converting this to a discussion topic since it isn't a bug.