Search code examples
pythoninner-classespython-typing

Python: typing, how to use an inner class from another inner class?


Is it possible to specify a parameter of an inner class function as being types as another inner class?

class MyClass():
    
    class InnerClass1():
        pass
        
    class InnerClass2():
        def func(self, param: InnerClass1):
            pass
        
if __name__ == '__main__':
    obj = MyClass()

This reports NameError: name 'InnerClass1' is not defined

Using param: MyClass.InnerClass1 reports NameError: name 'MyClass' is not defined

If this is not possible, what could be the alternative to correctly declare parameter type?


Solution

  • You can refer to the type by string:

    class MyClass():
        
        class InnerClass1():
    
            @property
            def name(self) -> str:
                return "name"
            
        class InnerClass2():
            def func(self, param: "MyClass.InnerClass1"):
                pass
            
    if __name__ == '__main__':
        obj = MyClass()
    
    

    This shows VS Code autocomplete working for param:

    VS Code autocomplete for property of an inner class