Home > Net >  Mypy type checker and "static instances"
Mypy type checker and "static instances"

Time:10-05

For a class A I wrote, there are some instances foo and bar that I want to be accessible through A.foo and A.bar as class variables. However, foo and bar are both instances of A, and I'm not sure how to let the typechecker mypy handle this correctly. I currently instantiate foo and bar as follows:

class A:
  def __init__(self):
    pass

  foo = None
  bar = None

A.foo = A()
A.bar = A()

Which leads mypy to conclude that A.foo and A.bar are of type None. Annotating as Optional[A] would work, but that's misrepresenting what is intended: I want both to be of type A... Any tips?

CodePudding user response:

If your using a higher version of python 3, you can use annotations to do this for you.

foo : A

I think mypy works with standard annotations. If this doesn't work, then try surrounding the annotation with quotes.

foo : "A"
  • Related