News for hackers. Stuff that matters.
Re:Approximating sum types in Python with Pydantic by ncbag on Thursday August 15, 2024 @06:12AM (#41254479)
Yes, the following is so easy in OCaml, it would be a major undertaking in Python:

  type committer =
    InnerCircle of string
  | NPC of string
  | Dissenter of string
  ;;

  type coc_reaction =
    DoNothing
  | ThreeMonthsWithoutHumiliation
  | PublicDefamation
  ;;

  let adjudicate = function
    InnerCircle _ -> DoNothing
  | NPC _ -> ThreeMonthsWithoutHumiliation
  | Dissenter _ -> PublicDefamation
  ;;

  # adjudicate (InnerCircle "Wouters");;
  - : coc_reaction = DoNothing
  # adjudicate (Dissenter "Peters");;
  - : coc_reaction = PublicDefamation
Just use another language, also for social and professional reasons.
Re:Approximating sum types in Python with Pydantic by masklinn on Thursday August 15, 2024 @08:10AM (#41255009)
As a matter of fact this would not be a "major undertaking" in Python, unless your definition of the term is majorly loose:

    @dataclass
    class InnerCircle:
        s: str

    @dataclass
    class NPC:
        s: str

    @dataclass
    class Dissenter:
        s: str

    Committer = Union[InnerCircle, NPC, Dissenter]

    class CocReaction(Enum):
        DoNothing = auto()
        ThreeMonthsWithoutHumiliation = auto()
        PublicDefamation = auto()

    def adjudicate(c: Committer) -> CocReaction:
        match c:
            case InnerCircle():
                return CocReaction.DoNothing
            case NPC():
                return CocReaction.ThreeMonthsWithoutHumiliation
            case Dissenter():
                return CocReaction.PublicDefamation
Although in reality you'd likely model Committer as a product of a status and name, and adjudicate as a map of status to reaction, unless there are other strong reasons to make Committer a sum.