1

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?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Knaapje
  • 165
  • 1
  • 1
  • 10
  • 1
    Why don't you just annotate it as `foo: A`? Why are you even setting it to `None` to begin with? – juanpa.arrivillaga Oct 04 '21 at 17:52
  • Because I can't instantiate instances of class A before the class definition has finished. – Knaapje Oct 04 '21 at 18:00
  • 3
    You **don't need to**. Just annotate the variable with `A` and instantiate it outside, like you just did. If you assign `None` then you *have* to use `Optional` – juanpa.arrivillaga Oct 04 '21 at 18:01
  • Huh. I just tried it before your comment, no idea that this was possible, TIL. – Knaapje Oct 04 '21 at 18:02
  • 1
    Note, you will have to use `from __future__ import annotations` if you want to be able to use `A` instead of `"A"`, unless you are already on Python 3.10 (where this will become the default behavior) – juanpa.arrivillaga Oct 04 '21 at 18:03

1 Answers1

1

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"
kinderhead
  • 36
  • 3
  • 4
    **Don't assign `None`**. That is incorrect. If you are going to use `None`, then it should be `Optional[A]`. Just use `foo: A` (using `from __future__ import annotations` if you need to be able to refer to an annotation before the variable is defined) – juanpa.arrivillaga Oct 04 '21 at 17:54
  • That's right. I forgot about that. Thanks – kinderhead Oct 04 '21 at 17:56