top | item 28604383

(no title)

azkae | 4 years ago

You can already do this without pattern matching:

  from typing import Union, NoReturn
  
  class Foo:
      name: str
  
  class Bar:
      size: int
 
  Variant = Union[Foo, Bar]       # or `Foo | Bar` in Python 3.10
  
  def assert_never(x: NoReturn) -> NoReturn:
      # runtime error, should not happen
      raise Exception(f'Unhandled value: {x}')
  
  def tell(x: Variant):
      if isinstance(x, Foo):
          print(f'name is {x.name}')
      elif isinstance(x, Bar):
          print(f'name is {x.size}')
      else:
          assert_never(x)
mypy returns an error if you don't handle all cases.

discuss

order

incrudible|4 years ago

The difference is that in Typescript, this works on any structurally matching object that you may get e.g. through JSON.