python instance function do not find type(class)


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()
    test.mylist = [TestX()]

if __name__ == "__main__":


Traceback (most recent call last):   
    File "", line 1, in <module>
        class TestX:   
    File "", line 5, in TestX
        def _get_mylist(self)->list[TestX]: 
NameError: name 'TestX' is not defined
Asked By: Hi10



You can use

def _get_mylist(self) -> list['TestX']:


def _get_mylist(self) -> list[__class__]:
Answered By: bitflip
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.