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 |1 Answer
Reset to default 3In 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
B: typing.ClassVar[Self]
. I'll find a dupe. – InSync Commented Mar 26 at 17:12