0

I am maintaining a collection of created objects within class:

class Foo:
    all_of_us: = []

    def __init__(self):
        Foo.all_of_us.append(self)

Which fails if I try to type annotate:

import typing

class Foo:
    all_of_us: typing.List[Foo] = []

With NameError: name 'Foo' is not defined.

What is the right way to go about it?

khelwood
  • 55,782
  • 14
  • 81
  • 108
y.selivonchyk
  • 8,987
  • 8
  • 54
  • 77

1 Answers1

3

you have two choices :

if you are using a recent version of python, you can use the annotations module from __future__ (that will store your annotations directly as strings without having to do it manually)

from __future__ import annotations
from typing import List

class Foo:
    all_of_us: List[Foo] = []

if you have an older version, simply put our class type inside a string manually:

from typing import List

class Foo:
    all_of_us: List['Foo'] = []
mrCopiCat
  • 899
  • 3
  • 15