最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - coc-pyright fail to report reportAttributeAccessIssue if __setattr__ is provided - Stack Overflow

programmeradmin1浏览0评论
from pydantic import BaseModel
class User2(BaseModel):
    name:str
    age: int
    '''
    def __setattr__(self, key, value):
        super().__setattr__(key, value)
    '''
user2 = User2(name="Alice", age=1)
>>> user2.foo = 1 # Should report: Cannot assign to attribute "foo" for class "User2" \ Attribute "foo" is unknown

if I uncomment the __setattr__ function, user2.foo = 1, coc-pyright doesn't report an error. I want to use a __setattr__ method but also have it report an error. How can I do this?

from pydantic import BaseModel
class User2(BaseModel):
    name:str
    age: int
    '''
    def __setattr__(self, key, value):
        super().__setattr__(key, value)
    '''
user2 = User2(name="Alice", age=1)
>>> user2.foo = 1 # Should report: Cannot assign to attribute "foo" for class "User2" \ Attribute "foo" is unknown

if I uncomment the __setattr__ function, user2.foo = 1, coc-pyright doesn't report an error. I want to use a __setattr__ method but also have it report an error. How can I do this?

Share Improve this question edited Mar 28 at 18:29 InSync 11.1k4 gold badges18 silver badges56 bronze badges asked Mar 28 at 7:14 user2976130user2976130 351 silver badge7 bronze badges 3
  • What error are you expecting it to report? – snakecharmerb Commented Mar 28 at 7:26
  • Cannot assign to attribute "foo" for class "User2" \ Attribute "foo" is unknown. I want to report this even setattr is overrided. I don't know whether it can be fixed by setting something to coc-pyright. – user2976130 Commented Mar 28 at 7:40
  • is "foo" a specific attribute or should this be handled equivalently for all attributes? – Daraan Commented Mar 28 at 8:32
Add a comment  | 

1 Answer 1

Reset to default 2

The presence of __setattr__ does not report reportAttributeAccess issue for pyright as well as mypy. The trick is to not reveal that such a method exists. This can be done by defining it in an if not TYPE_CHECKING: block. Linters and checkers might mark the code there as unreachable which can be undesired, therefore you can redirect the call to a normal private method that is executed instead:

from pydantic import BaseModel
from typing import TYPE_CHECKING


class User2(BaseModel):
    name: str
    age: int

    if not TYPE_CHECKING:
        # hide from type-checker to report AttributeAccessIssue
        def __setattr__(self, key, value):
            self._setattr(key, value)

    # Use a different method to not create "unreachable code"
    def _setattr(self, key, value):
        super().__setattr__(key, value)


user2 = User2(name="Alice", age=1)
user2.foo = 1  # reportAttributeAccess 
发布评论

评论列表(0)

  1. 暂无评论