Parsing in Python has never been easier
Project description
Nothing (almost) should ever be any str or any int
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
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(User, raw))
User(id=1, name='Fred', hobbies=['origami', 'curling', 'programming'])
Installation
Install from PyPI:
pip install valtypes
Build the latest version from source:
pip install git+https://github.com/LeeeeT/valtypes
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
valtypes-6.0.0.tar.gz
(17.7 kB
view hashes)
Built Distribution
valtypes-6.0.0-py3-none-any.whl
(33.3 kB
view hashes)