3

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?

4
  • A class usually should not depend on the existence of any particular subclasses. What's your use case for this? Commented Nov 13, 2022 at 2:37
  • @chepner a bit more detail is here: stackoverflow.com/questions/74417988/… Commented Nov 13, 2022 at 2:38
  • 1
    That doesn't answer my question. Why would a type require a subtype in order to instantiate it? Commented Nov 13, 2022 at 2:45
  • @chepner it probably wouldn't or shouldn't, to be honest this is my first time trying to design a sort of type hierarchy like this so sort of playing around with it a bit... Commented Nov 13, 2022 at 9:39

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.