Do union types actually exist in python?

前端 未结 4 1700
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 02:30

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

4条回答
  •  情深已故
    2020-12-10 03:04

    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.

提交回复
热议问题