1

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?

2
  • @Georgy I simply put the name in quotes in the type definition.
    – Jonathan
    Jun 30, 2020 at 0:05
  • @Georgy, By the way, I am using Python 3.8.3 so some of the material from PEP_0563 is in Python, I did not need to import from __future__
    – Jonathan
    Jun 30, 2020 at 0:12

1 Answer 1

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.