Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()
    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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use

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

or

def _get_mylist(self) -> list[__class__]:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading