Since python is dynamically typed, of course we can do something like this:
def f(x):
return 2 if x else \"s\"
But is this the way pyth
Here are a couple of options to deal with use-cases where you need a tagged union/sum type in Python:
Enum + Tuples
from enum import Enum
Token = Enum('Token', ['Number', 'Operator', 'Identifier', 'Space', 'Expression'])
(Token.Number, 42) # int type
(Token.Operator, '+') # str type 1
(Token.Identifier, 'foo') # str type 2
(Token.Space, ) # no data
(Token.Expression, 'lambda', 'x', 'x+x') # multiple data
isinstance
if isinstance(token, int):
# Number type
if isinstance(token, str):
# Identifier type
sumtypes module
These approaches all have their various drawbacks, of course.