Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type one of several classes

Let’s say I have the following two classes:

class Literal:
    pass

class Expr:
    pass

class MyClass:
    def __init__(self, Type:OneOf(Literal, Expr)):
        pass

How would I make the type one of the Expr or Literal class? The full example of what I’m trying to do is as follows:

from enum import Enum
PrimitiveType = Enum('PrimitiveType', ['STRING', 'NUMBER'])

class Array:
    def __init__(self, Type:OneOf[Array,Struct,PrimitiveType]):
        self.type = Type

class Pair:
    def __init__(self, Key:str, Type:OneOf[Array,Struct,PrimitiveType]):
        self.Key = Key
        self.Type = Type

class Struct:
    def __init__(self, tuple[Pair])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You want a Union type:

from typing import Union

def __init__(self, Key: str, Type: Union[Array, Struct, PrimitiveType]):

# or in 3.10+

def __init__(self, Key: str, Type: Array | Struct | PrimitiveType):
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading