Search code examples
pythonpython-3.xtyping

Referring to the class name within a type definition in the class body


I have problems referencing the class name in typing statements with the class in question. The following code shows the problem:

class C():
    def __init__(self, a: C)
        self.a = a

    @property
    def a(self) -> C:
        return self.a

The compiler complains that C is undefined. Is what I am trying to do impossible and will I have to abandon the use of typing for this class?


Solution

  • You can solve it with this import from __future__ import annotations PEP-0563:

    from __future__ import annotations
    
    class C:
        def __init__(self, a: C):
            self.a = a
    
        @property
        def a(self) -> C:
            return self.a
    

    Or simply use a string:

    class C:
        def __init__(self, a: 'C'):
            self.a = a
    
        @property
        def a(self) -> 'C':
            return self.a