Skip to content
This repository has been archived by the owner on Jun 12, 2024. It is now read-only.

LeeeeT/valtypes

Repository files navigation

Nothing (almost) should ever be any str or any int


Documentation: valtypes.readthedocs.io

Source code: github.com/LeeeeT/valtypes


What is valtypes

Valtypes is a flexible data parsing library which will help you make illegal states unrepresentable and enable you to practice "Parse, don’t validate" in Python. It has many features that might interest you, so let's dive into some examples.

Examples

Create constrained types:

from valtypes.type.str import NonEmpty, MaximumLength


class Name(NonEmpty, MaximumLength):
    __maximum_length__ = 20

    
def initials(name: Name) -> str:
    # name is guaranteed to be a non-empty string of maximum length 20
    return f"{name[0]}."


initials(Name("Fred"))  # passes
initials(Name(""))  # parsing error
initials("")  # fails at static type checking

Parse complex data structures:

from dataclasses import dataclass

from valtypes import parse_json
from valtypes.type import int, list, str


@dataclass
class User:
    id: int.Positive
    name: Name
    hobbies: list.NonEmpty[str.NonEmpty]


raw = {"id": 1, "name": "Fred", "hobbies": ["origami", "curling", "programming"]}

print(parse_json(User, raw))
User(id=1, name='Fred', hobbies=['origami', 'curling', 'programming'])

Get a nice error message if something went wrong (traceback omitted):

raw = {"id": 0, "hobbies": [""]}

parse_json(User, raw)
| valtypes.error.parsing.dataclass.Composite: dataclass parsing error (3 sub-exceptions)
+-+---------------- 1 ----------------
  | valtypes.error.parsing.dataclass.WrongFieldValue: can't parse field 'id' (1 sub-exception)
  +-+---------------- 1 ----------------
    | valtypes.error.parsing.type.numeric.Minimum: the value must be greater than or equal to 1, got: 0
    +------------------------------------
  +---------------- 2 ----------------
  | valtypes.error.parsing.dataclass.MissingField: required field 'name' is missing
  +---------------- 3 ----------------
  | valtypes.error.parsing.dataclass.WrongFieldValue: can't parse field 'hobbies' (1 sub-exception)
  +-+---------------- 1 ----------------
    | valtypes.error.parsing.sequence.Composite: sequence parsing error (1 sub-exception)
    +-+---------------- 1 ----------------
      | valtypes.error.parsing.sequence.WrongItem: can't parse item at index 0 (1 sub-exception)
      +-+---------------- 1 ----------------
        | valtypes.error.parsing.type.sized.MinimumLength: length 0 is less than the allowed minimum of 1
        +------------------------------------

Installation

Install from PyPI:

pip install valtypes

Build the latest version from source:

pip install git+https://github.com/LeeeeT/valtypes