Skip to main content

Py Sum Types

Build Status

Simple syntax to declare, match, compare, and unwrap sum types for Python

Sum Types, aka Discriminated Unions are a kind of Algebraic Data Type (ADT) found in strongly typed functional languages (among other places).

type Success = {Data: string}
type Failure = {ErrorCode: int; ErrorMessage: string}
type Response =
    | Succeeded of Success
    | Failed of Failure

let example(a: int) =
    if (a > 0) then
        Response.Succeeded <| {Data="Data!"}
    else
        Response.Failed <| { ErrorCode=401; ErrorMessage="Nope"}

let response = example(22)

match response with
    | Response.Succeeded s -> printf "%s\n" s.Data
    | Response.Failed f -> printf "%s\n" f.ErrorMessage

Definition & Useage

So how might we do this in Python?

Definition

@dataclass
class Success:
    data: str
    count: int

@dataclass
class Failure:
    error_code: int
    error_message: str

@sumtype
class Response:
    success: Success
    failure: Failure

Useage

def example(a:int) -> Response:
    if a > 0:
        return Response(Failure(error_code=403, error_message='Not Today'))
    return Response(Success('Wow such data', count=500))

response = example(22)

if response.match(Success):
    print('Look at this data {}'.format(response.data))
    actual_instance = response.unwrap()
    actual_instance.count += 1000
else:
    print('Oh what have we done sweet corgi buns!!! Error: {}'.format(response.error_message))
    if response == Failure(403, 'Not Today'):
        print('Not today!!!')

Exceptions

x = example(22)
print('Look at this data {}'.format(x.data))
# raises a SumTypeAttributeNotFound exception
@dataclass
class Failcess:
    error_message: str
    error_code: int

@sumtype
class TooManyTypes:
    success: Success
    hurray: Success
    fail: Failure
    oops: Failure

def example(a) -> TooManyTypes:
    return TooManyTypes(Success('Wow such data', 500))
    # raises a SumTypeInitError exception
    # Sum Types should have unique types

Metadata

Release files for PySumTypes 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for PySumTypes 0.0.1
File Interpreter ABI Platform
PySumTypes-0.0.1-py3-none-any.whl Python 3 none any Details

Release files / PySumTypes-0.0.1-py3-none-any.whl

Download URL PySumTypes-0.0.1-py3-none-any.whl
Size 4.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e71dfbaa185afaec3baf1d54232ee120c218c29391255775051ee8922fcdb1c7
BLAKE2b-256 checksum
How to use checksums
1ba92997e4e64c6a0b5e87068497c797a0f543c32051ab0404e92e291800b908
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.23.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.3

Release history Release notifications | RSS feed

This release

0.0.1 This release

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page