0

TestX is class has mylist as property, mylist returns the collection of TestX objects, below is the sample code, at line #5 getting an error "'TestX' is not declared", if TestX is removed then no error code works fine, the only question here why Python do not recognize type name in same type at collection, if preemptive/system types like int, str etc.. then type name is recognized.

class TestX:
    def __init__(self) -> None:
        self._mylist:list[TestX] = [] 

    def _get_mylist(self)->list[TestX]: #This line error out
        return self._mylist

    def _set_mylist(self,value):
        self._mylist = value

    mylist = property(fget=_get_mylist,fset=_set_mylist,doc="This is test")

def main():
    test = TestX()
    print(len(test.mylist))
    test.mylist = [TestX()]
    print(len(test.mylist))

if __name__ == "__main__":
    main()

Result

Traceback (most recent call last):   
    File "D:\code\test.py", line 1, in <module>
        class TestX:   
    File "D:\code\test.py", line 5, in TestX
        def _get_mylist(self)->list[TestX]: 
NameError: name 'TestX' is not defined
Hi10
  • 531
  • 1
  • 5
  • 21

1 Answers1

0

You can use

def _get_mylist(self) -> list['TestX']:
bitflip
  • 3,436
  • 1
  • 3
  • 22