python - mypy complains for static variable - Stack Overflow

mypy (v.1.15.0) complains with the following message Access to generic instance variables via class is

mypy (v.1.15.0) complains with the following message Access to generic instance variables via class is ambiguous for the following code:

from typing import Self

class A:
    B: Self
    
A.B = A()

If I remove B: Self, then is says "type[A]" has no attribute "B".

How make mypy happy? You can play with this here: mypy playground

mypy (v.1.15.0) complains with the following message Access to generic instance variables via class is ambiguous for the following code:

from typing import Self

class A:
    B: Self
    
A.B = A()

If I remove B: Self, then is says "type[A]" has no attribute "B".

How make mypy happy? You can play with this here: mypy playground

Share Improve this question edited Mar 26 at 17:12 InSync 11.1k4 gold badges18 silver badges56 bronze badges asked Mar 26 at 16:59 PinkFloydPinkFloyd 2,2154 gold badges29 silver badges48 bronze badges 3
  • 2 It should be B: typing.ClassVar[Self]. I'll find a dupe. – InSync Commented Mar 26 at 17:12
  • Potential dupe targets: Python class members type hinting, Type Hints Convention for Instance Variables Python. Neither of them are particularly good targets, but I can't find a better one. – InSync Commented Mar 26 at 17:25
  • @InSync If you post your comment as an answer, I'll accept it... thx – PinkFloyd Commented Mar 26 at 17:56
Add a comment  | 

1 Answer 1

Reset to default 3

In addition to InSync's solution, you can also do this:

class A:
    B: 'A'
    
A.B = A()

Or better yet:

from typing import ClassVar

class A:
    B: ClassVar['A']
    
A.B = A()

This is an example of a forward reference, and mypy handles those by putting the type name in quotes. Using ClassVar just tells the type checker to disallow setting B through an instance, since it's supposed to be static.
I prefer this over Self because the concept of self in programming usually refers to a specific instance, which doesn't make sense in the context of a static variable.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744137294a4560118.html

相关推荐

  • python - mypy complains for static variable - Stack Overflow

    mypy (v.1.15.0) complains with the following message Access to generic instance variables via class is

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信