Search code examples
pythonpython-typingsum-type

How to create Haskell-like sum types in Python?


If I have some simple sum type in Haskell, like

data Owner = Me | You

How do I express that in Python in a convenient way?


Solution

  • An Enum or a Union is the closest thing to a tagged union or sum type in Python.

    Enum

    from enum import Enum
    
    class Owner(Enum):
        Me = 1
        You = 2
    

    Union

    https://docs.python.org/3/library/typing.html#typing.Union

    import typing
    
    class Me:
        pass
    class You:
        pass
    
    owner: typing.Union[Me, You] = Me