• Stars
    star
    365
  • Rank 116,851 (Top 3 %)
  • Language
    Python
  • License
    Do What The F*ck ...
  • Created over 7 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PySchemes is a library for validating data structures in python

PySchemes

PySchemes is a library for validating data structures in Python. PySchemes is designed to be simple and Pythonic.

https://travis-ci.org/shivylp/pyschemes

Features

  • Simple representation of schema using primitive Python types (Or Complex types as well)
  • Sane Schema Structures
  • Sane errors
  • Power of PySchemes lies in its validators (take a look at tests to understand usage of various validators)
  • Lambda functions or any callable can be easily used as a validator

Examples

# Execute this before executing any of the examples
>>> from pyschemes import Scheme, validators
  1. Simple TypeChecking
>>> Scheme(int).validate(10)
10

>>> Scheme(int).validate(10.3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected type: 'int', got 'float'

>>> from collections import Iterable
>>> Scheme(Iterable).validate([1, 2])
[1, 2]

>>> Scheme(Iterable).validate(("hello", ))
("hello", )

>>> Scheme(Iterable).validate({"a": "b", "c": "d"})
{"a": "b", "c": "d"}

>>> Scheme(Iterable).validate(range(100))
range(0, 100)

>>> Scheme(Iterable).validate(lambda x: x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected type: 'Iterable', got 'function'
  1. Simple Value Validation
>>> Scheme(10).validate(10)
10

>>> Scheme(10).validate(10.3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: expected value '10', got '10.3'
  1. Simple Choices Validation
>>> choices = validators.Any(["choiceA", "choiceB", "choiceC"])

>>> Scheme(choices).validate("choiceA")
'choiceA'

>>> Scheme(choices).validate("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: value did not pass any validation
  1. Validating a List/Iterable Scheme
>>> Scheme([str, 2, int]).validate(["hello", 2, 15])
["hello", 2, 15]

>>> Scheme((str, 2, int)).validate(("hello", 2, 15))
("hello", 2, 15)

>>> Scheme((str, 2, int)).validate(["hello", 2, 15])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected type: 'tuple', got 'list'

>>> Scheme([str, 2, int]).validate(["hello", 3, 130])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: element at index 1 (expected value '2', got '3')

>>> Scheme([str, 2, int]).validate(["hello", 2, 4.5])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: element at index 2 (expected type: 'int', got 'float')
  1. Validating a Dictionary/Mapping Scheme
>>> Scheme({str: int}).validate({"a": 1, "b": 2})
{'a': 1, 'b': 2}

>>> Scheme({str: int}).validate({"a": 1, "b": 3.5})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: at key 'b' (expected type: 'int', got 'float')

>>> Scheme({"hello": 10, str: object}).validate({"hello": 10, "world": 12})
{"hello": 10, "world": 12}

>>> Scheme({"required-key": int}).validate({})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: missing key 'required-key'

>>> from pyschemes.validators import Optional
>>> Scheme({"k": Optional(str, "hello")}).validate({})
{'k': 'hello'}

>>> Scheme({"k": Optional(str, "hello")}).validate({"k": "world"})
{'k': 'world'}

>>> Scheme({"k": Optional(int, 10)}).validate({"k": "world"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: at key 'k' (expected type: 'int', got 'str')

>>> Scheme({"only-key": str}).validate({"only-key": "hello", "b": "not-allowed"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: at key 'b' (not allowed)
  1. Lambda/Callable Scheme
>>> Scheme(lambda x: x < 100).validate(10)
10

>>> Scheme(lambda x: x < 100).validate(101)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: validator '<lambda>' failed for value '101'

>>> def CustomValidator(value):
...    if value == "foo" or value in range(100):
...       return value
...    else:
...       return False
...
>>> Scheme(CustomValidator).validate(101)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: validator 'CustomValidator' failed for value '10'

>>> Scheme(CustomValidator).validate(9)
9
>>> Scheme(CustomValidator).validate("foo")
'foo'
  1. Compund Schemes
>>> Scheme({"test": lambda x: x < 100}).validate({"test": 10})
{'test': 10}

>>> Scheme({"test": lambda x: x < 100}).validate({"test": 101})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: at key 'test' (validator '<lambda>' failed for value '101')

>>> Scheme({"test": Scheme({"a": str, "b": int})}).validate({"test": {}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: at key 'test' (missing key 'a')

>>> Scheme({"test": Scheme({"b": int})}).validate({"test": {"b": 1.5}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: at key 'test' (at key 'b' (expected type: 'int', got 'float'))

>>> Scheme({"t": {str: int}}).validate({"t": {"a": 1}})
{'t': {'a': 1}}

>>> Scheme({"t": (str, int)}).validate({"t": ("a", 1)})
{'t': ('a', 1)}

And more to come in tests!

More Repositories

1

droplets

Droplets is a platform for Gophers.
Go
321
star
2

fabric

Fabric is a simple triplestore written in Golang
Go
197
star
3

radium

radium is a platform (client and optional server) for viewing reference articles, cheat sheets, snippets etc.
Go
61
star
4

skit

Build slack bots quickly and easily!
Go
45
star
5

delayq

DelayQ is a Go library that provides a performant, reliable, distributed delay-queue using Redis.
Go
39
star
6

slurp

Slurp is a highly customisable LISP toolkit for Go applications. 💻
Go
34
star
7

parens

Parens is a highly flexible and embeddable LISP toolkit. 💻
Go
33
star
8

radio

Radio is a library for creating RESP (REdis Serialization Protocol) comaptible services. 📻
Go
31
star
9

sabre

Sabre is highly customisable, embeddable LISP engine for Go. 💻
Go
28
star
10

sukit

Supabase + SvelteKit SaaS template.
Svelte
25
star
11

fusion

💥 Fusion is a tiny stream processing library written in Go.
Go
17
star
12

kiwi

Kiwi is a multi-backend key-value store written in Go.
Go
13
star
13

taurishell

A Raycast/Spotlight like app shell using https://tauri.studio/
Rust
12
star
14

slang

Slang (short for Sabre Lang) is a tiny LISP dialect built using Sabre
Go
7
star
15

avabot

A ChatGPT personal assistant bot on Telegram
TypeScript
6
star
16

forge

Where the apps are forged! 🔥
Go
6
star
17

moonshot

🌔 A boilerplate Go library for quickly setting up backend for your next moonshot idea!
Go
4
star
18

pkg

Random, re-usable, probably useful packages.
Go
3
star
19

envision

Envision is a dynamic system simulator similar to Simulink.
C#
3
star
20

goworm

🐛 GoWorm is a simulation tool for simple point neuron based spiking neural network models.
Go
2
star
21

connote

📝 connote is a dead-simple console-based note taking tool.
Go
2
star
22

cats-and-dogs

cats-and-dogs is a Convolutional Neural Network for classifying cats and dog pictures.
Python
1
star
23

enforcer

Enforcer is a dynamic rule based workflow/journey system
Go
1
star
24

myvim

My (neo)Vim configurations
Vim Script
1
star
25

liftoff

🚀 A sample React application for quickly getting started.
TypeScript
1
star
26

snowman

⛄️ Snowman is a Go library & tool for building chatbots.
Go
1
star
27

ticktock

Go
1
star
28

churn-prediction

Customer churn prediction using Deep Neural Network.
Python
1
star