Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 810
dmvianna Avatar asked Oct 27 '25 14:10

dmvianna


1 Answers

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
like image 139
Ben Avatar answered Oct 30 '25 06:10

Ben