Home > Software engineering >  Type one of several classes
Type one of several classes

Time:11-13

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])

CodePudding user response:

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):

CodePudding user response:

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])
  • Related