3

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?

dmvianna
  • 15,088
  • 18
  • 77
  • 106
  • Does this answer your question? [How to specify multiple return types using type-hints](https://stackoverflow.com/questions/33945261/how-to-specify-multiple-return-types-using-type-hints) – Georgy Feb 22 '21 at 09:04
  • @Georgy Unfortunately no. That answer shows how to express `classes` of values, i.e., `int` or `str`. I want to limit it to `values`, i.e., `1` and `2`, or the strings `me` and `you`. – dmvianna Feb 22 '21 at 09:18
  • 1
    Oh, I see. Then you are looking for [`typing.Literal`](https://docs.python.org/3.8/library/typing.html#typing.Literal). Here is a fitting duplicate question: [Type hint for a function that returns only a specific set of values](https://stackoverflow.com/q/39398138/7851470) – Georgy Feb 22 '21 at 10:03
  • Are you looking for static types or runtime types? An enum might be appropriate for the latter. – MisterMiyagi Feb 22 '21 at 18:01
  • For the other commenters the poster is asking about a tagged union or sum types https://en.wikipedia.org/wiki/Tagged_union – Fuji Apr 21 '21 at 08:32
  • Does this answer your question? [How can I define algebraic data types in Python?](https://stackoverflow.com/questions/16258553/how-can-i-define-algebraic-data-types-in-python) – joel Aug 10 '22 at 01:36

1 Answers1

4

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

Fuji
  • 28,214
  • 2
  • 27
  • 29
  • 2
    It would be helpful if you could try to translate the sample given in the question. While these constructs are theoretically close, it's not entirely clear to me that these two actually match the desired *effect*. Since Python values are natively "tagged" with their type, the effect of a tagged union may be achieved otherwise – for example, by doing nothing. – MisterMiyagi Apr 21 '21 at 08:43