Skip to main content

Python typing that raise TypeError at runtime

Project description

madtypes

  • 💢 Python class typing that raise TypeError at runtime
  • 📖 Render to dict or json
  • 🌐 Json-Schema

Example

from madtypes import Schema

class Item(Schema)
    name: str

Item() # raise TypeError, name is missing
Item(name=2) # raise TypeError, 2 is not an str
Item(name="foo") # ok

repr(Item(name="foo")) == {"name": "foo"}
json.dumps(Item(name="foo")) => '{"name": "foo"}'

from typing import Optional
class ItemWithOptional(Schema):
    name: Optional[str]

ItemWithOptional() # ok

Immutables

from madtypes import Immutable # Immutable inherits from Schema

class Foo(Immutable):
    name: str
    age: Optional[int]

e = Foo(name="foo")

e.name = "bar" # raise TypeError


b = Foo(**e) # intianciate a new copy
b = Foo(age=2, **e) # create a copy with changes

json-schema

from madtypes import schema, Schema
from typing import Optional

class Item(Schema):
    name: Optional[str]

class Basket(Schema):
    items: list[Item]

assert schema(Basket) == {
    "type": "object",
    "properties": {
        "items": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {"name": {"type": "string"}},
            },
        }
    },
    "required": ["items"]
}

Test pypi python: >3.9

Installation

pip3 install madtypes

Context

madtypes is a Python3.9+ library that provides enhanced data type checking capabilities. It offers features beyond the scope of PEP 589 and is built toward an industrial use-case that require reliability.

  • The library introduces a Schema class that allows you to define classes with strict type enforcement. By inheriting from Schema, you can specify the expected data structure and enforce type correctness at runtime. If an incorrect type is assigned to an attribute, madtypes raises a TypeError.

  • Schema class and it's attributes inherit from dict. Attributes are considered values of the dictionnary.

  • It renders natively to JSON, facilitating data serialization and interchange.

  • The library also includes a schema() function that generates JSON-Schema representations based on class definitions.

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

madtypes-0.0.3.tar.gz (5.0 kB view hashes)

Uploaded Source

Built Distribution

madtypes-0.0.3-py3-none-any.whl (3.6 kB view hashes)

Uploaded Python 3

Supported by

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