4

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?

6
  • Does this answer your question? How to specify multiple return types using type-hints Commented Feb 22, 2021 at 9: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. Commented Feb 22, 2021 at 9:18
  • 1
    Oh, I see. Then you are looking for typing.Literal. Here is a fitting duplicate question: Type hint for a function that returns only a specific set of values Commented Feb 22, 2021 at 10:03
  • Are you looking for static types or runtime types? An enum might be appropriate for the latter. Commented Feb 22, 2021 at 18:01
  • For the other commenters the poster is asking about a tagged union or sum types en.wikipedia.org/wiki/Tagged_union Commented Apr 21, 2021 at 8:32

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.