Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-like forward declaration in python class

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?

like image 354
David542 Avatar asked Mar 03 '26 17:03

David542


1 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
like image 98
kosciej16 Avatar answered Mar 06 '26 08:03

kosciej16



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!