Skip to main content

Dependent types for Python

Project description


Dependent types for Python.


python3 -m pip install dependent-types


  • Make illegal states unrepresentable.
  • Parse, don't validate
  • Abuse __instancecheck__ and type-guards.
  • Values are checked at runtime but no extra instances/subclasses are instantiated.


Builtin types


  • TZAware
  • TZNaive


  • Natural
  • NegativeInt
  • Portion

  • Match


  • NonEmpty
  • Empty

Creating dependent types

To create new dependent types, subclass dept.base.Dependent and define an __instancecheck__ method:

from typing import Any
from typing import TYPE_CHECKING

from dept.base import Dependent

class Greeting(str, Dependent):
    def __instancecheck__(cls, instance: Any) -> bool:
        return (
            isinstance(instance, str)
            and instance.startswith(("Hello", "Hi"))

hello = "Hello there"
# We can narrow types using mypy's type guards
assert isinstance(hello, Greeting)
# or explicitly when we need to
hi = Greeting.from_instance("Hi there")

# The runtime types are unchanged and will still be str for our greetings
assert type(hello) is str
assert type(hi) is str

# But their static types will be Greeting, retaining the information that our
# strings are not just any strs

# As this string doesn't fulfill our __instancecheck__, it will not be an
# instance of Greeting.
assert not isinstance("Goodbye", Greeting)

Checkout out the dacite example for how to create dataclasses with rich dependently typed fields without duplicating type definitions or losing parsed information.

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

dependent-types-0.0.1.tar.gz (6.5 kB view hashes)

Uploaded source

Built Distribution

dependent_types-0.0.1-py3-none-any.whl (8.6 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page