Skip to main content

Algebraic Data Types in Python

Project description

Build badge Codecov badge Documentation Status

Algebraic Data Types in Python

import adt

class MyADT(adt.ADT):
    foo: ()
    bar: (int,)
    baz: (int, bool, str, None)

    @adt.fieldmethod
    def double_first(field, basecls) -> "MyADT":
        if isinstance(field, basecls.foo):
            raise TypeError(
                f"{basecls.foo.__qualname__} does not support doubling"
            )
        field_type = type(field)
        first, *rem = field
        return field_type(first * 2, *rem)

foo = MyADT.foo()
bar = MyADT.bar(4)
baz = MyADT.baz(3, False, "hi", None)

for val in [foo, bar, baz]:
    print(val)
    try:
        doubled = val.double_first()
        print("Doubled:", doubled)
    except TypeError:
        print("Failed to double")
    print()

See examples/, adt/example.py and tests/test.py.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

adt-0.0.2.tar.gz (8.5 kB view details)

Uploaded Source

Built Distribution

adt-0.0.2-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

Details for the file adt-0.0.2.tar.gz.

File metadata

  • Download URL: adt-0.0.2.tar.gz
  • Upload date:
  • Size: 8.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.1

File hashes

Hashes for adt-0.0.2.tar.gz
Algorithm Hash digest
SHA256 be7c3fd319affeae73080d6b3b6b09df6e342612ca0a525ed7cf924dd05f7004
MD5 39db36b72937c7e3f4df86b5f5dfaa2a
BLAKE2b-256 0c9273c650f270f8f2d0f84aa95e35fb0e14a4f25fa987d00b8c1cb6fd856437

See more details on using hashes here.

File details

Details for the file adt-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: adt-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 5.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.1

File hashes

Hashes for adt-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9c36d5a1004dec40a2964b944d9cd5d4088742f13a4c0c06075a47c05a46802e
MD5 fb762f4b15e7c166b135b6e2d88b8ed5
BLAKE2b-256 50e07ea4c68d9379da8d39fb85018eae13795bd74a3fbc0bfb0521e46fab3523

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page