Type one of several classes

Question:

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])
Asked By: David542

||

Answers:

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):
Answered By: Carcigenicate

You can refer post:
How to express multiple types for a single parameter or a return value in docstrings that are processed by Sphinx?

from typing import Union

and

def __init__(self, Type:Union[Array,Struct,PrimitiveType])
Answered By: Brijesh Varsani
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.