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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Jonathan
  • 2,635
  • 3
  • 30
  • 49
  • @Georgy I simply put the name in quotes in the type definition. – Jonathan Jun 30 '20 at 00: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 '20 at 00:12

1 Answers1

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91