pythonpython-typingmypy

mypy complains for static variable


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


Solution

  • 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.