C-like forward declaration in python class

Question:

How would I properly do the following in python?

class AnyType:
    def __init__(self, Type:Union[PrimitiveType, ComplexType]):
        self.Type = Type

class PrimitiveType(AnyType):
    def __init__(self, Type):
        super().__init__(Type)

class NestedType(AnyType):
    def __init__(self, Type):
        super().__init__(Type)

NameError: name ‘PrimitiveType’ is not defined

I know in C there is a forward declaration but how do I prevent the following circular reference in python?

Asked By: David542

||

Answers:

There is a PEP describing such feature. If you use python3.7+ you can add from __future__ import annotations at the beginning and it should work. In other case, using string fixes the problem

class AnyType:
    def __init__(self, Type:Union["PrimitiveType", "ComplexType"]):
        self.Type = Type
Answered By: kosciej16
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.