CLI tool
keleshev/schema avatar
keleshev/schema

keleshev/schema: validating Python data structures with Schema, And and Use

Schema validation just got Pythonic

2,938 stars235 forksPythonMIT

At a glance

What is it?
A small MIT-licensed Python library that validates dicts, lists and scalars by composing types, callables and converters. It is at its best around JSON and YAML payloads, and it is not a JSON Schema implementation.
Who is it for?
Adopt keleshev/schema when you already have Python data in hand (parsed JSON, YAML, form fields, argparse output) and want validation rules that read like ordinary Python expressions. Do not adopt it if you need a declarative document format that other languages can consume, or if you need to reject unknown keys by default, since the README shows no such mode.
Can I use it commercially?
Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
Is it still maintained?
Yes. The repository last received commits 155 days ago.
What is it written in?
Mainly Python, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on November 19, 2026, and from our analysis. They are not legal advice.

From daily snapshots

Star history

  • keleshev/schema2,938 ★ · -8
Star history
Repository2026-09-242026-11-19
keleshev/schema2.9k2.9k

-8 Stars in the last 56 days, measured from the daily GitHub snapshot. Compare with other projects

Editorial analysis

The problem keleshev/schema solves, and who has it

Data that arrives from outside your program rarely has the shape your code assumes. The README names the usual sources: config files, forms, external services, and command-line parsing, converted from JSON or YAML into Python data types. Once parsed, a JSON object is just a dict of strings, lists and numbers. Nothing in the standard library tells you that the age field is an integer between 18 and 99, or that the gender field, when present, holds one of two lowercase words.

The library's answer is to describe the expected shape as a Python expression and hand the actual data to Schema.validate. The README's opening example builds a schema for a list of people, where name must be a non-empty string, age must convert to an integer in a range, and gender is optional and normalised to lowercase before being checked against a fixed set. The audience is Python developers writing that glue code: parsers for configuration, request handlers that read a body, scripts that consume someone else's API. If your data already lives in typed Python objects produced by an ORM or a dataclass, this library adds little.

How Schema validates: types, callables, validatables and containers

Validation is recursive and dispatch is by the kind of object found in the schema, not by a separate rule language. The README documents four cases.

A type in the schema means an isinstance check on the data. Schema(int).validate('123') fails with SchemaUnexpectedTypeError, and the README shows the message: '123' should be instance of 'int'. A callable means the library calls it and requires a truthy result, so Schema(os.path.exists).validate('./') returns the path while a non-existent one raises SchemaError. An object with a validate method is a validatable: the library calls data = obj.validate(data) and lets it raise SchemaError. Regex and Use are the two examples given. Use wraps a function or type and converts the value, which is why And(Use(int), ...) turns the string "28" into the integer 28 in the README's example.

Containers aggregate errors rather than stopping at the first one. For a list, tuple, set or frozenset, the contents are validated against every schema listed inside the container, and the README shows a tuple schema (int, float) producing two separate messages for one bad element, one for int and one for float. Dicts validate key-value pairs, and keys can themselves be schemas. The README also shows Const, which validates a value and then puts the original back, so a timestamp can be checked as a future date and still be serialised unchanged.

Installing keleshev/schema and a first real validation

The README gives one install path, pip, and notes that you can drop schema.py into your project instead because the file is self-contained.

bash
pip install schema

The only declared dependency in requirements.txt is contextlib2 for Python versions below 3.3, so on any current interpreter the install pulls nothing else. The package layout is a schema/ directory with setup.py reading the version from schema/__init__.py, and the classifiers in setup.py list Python 3.6 through 3.11 plus PyPy, while the README's own test claim covers 2.6 through 3.9 and PyPy.

For a first use, take the README's example shape and apply it to a parsed JSON payload. The schema below requires a name of non-empty string, coerces age with Use(int), checks the range with a lambda, and treats gender as optional, lowercasing it before checking membership.

python
from schema import Schema, And, Use, Optional, SchemaError

schema = Schema(
    [
        {
            "name": And(str, len),
            "age": And(Use(int), lambda n: 18 <= n <= 99),
            Optional("gender"): And(
                str,
                Use(str.lower),
                lambda s: s in ("squid", "kid"),
            ),
        }
    ]
)

Calling schema.validate(data) returns the validated data with conversions applied, so an entry with age "28" comes back with the integer 28 and a gender of "Squid" comes back as "squid". If you only need a yes or no answer, the README states that schema.is_valid(data) returns True or False and does not raise. Wrap the call in a try block when you want to report the failure:

python
try:
    validated = schema.validate(data)
except SchemaError as e:
    print(e)

The exception message is what you show a user or log, and it carries the failing rule and the offending value.

Where keleshev/schema is the wrong tool

The library is a Python expression evaluator wearing a validation hat. That design buys readability and costs portability. A schema written with And, Use and Optional cannot be serialised to a file that a JavaScript service or a Go program can read. If your validation rules need to travel, for example a contract shared between a backend and a frontend, this is not the format for it, and the README does not claim otherwise.

The second limitation is strictness. The README's dict example validates the keys it names, and the Optional marker is used to make a key non-required. It does not document a mode that rejects keys the schema never mentions, so a payload with extra fields passes unless you write rules for them. Teams that treat unknown keys as an error will have to add that check themselves.

The third is the Python version story. The README claims testing on 2.6 through 3.9 and PyPy, while setup.py classifies 3.6 through 3.11, so the two lists do not agree. Neither is a statement about newer interpreters. On a Python release outside both lists, you are relying on the library's simplicity rather than on a tested claim. Finally, validation is not parsing: Use(int) on the string "abc" raises SchemaError from the wrapped callable, which is the behaviour you want, but it means the library never repairs malformed data, only rejects or converts it.

Alternatives and the difference in approach

The closest alternative is a JSON Schema validator such as jsonschema. The difference is where the rules live. JSON Schema rules are data: a dict or a file that can be stored, versioned, served over HTTP and consumed by validators in many languages. keleshev/schema rules are Python objects built at runtime, so they can call os.path.exists, close over local variables, or use any function you have. The trade is that JSON Schema cannot call your code, and keleshev/schema cannot be handed to a non-Python service.

A second alternative is a typed parsing library in the pydantic style, where you declare a model and get both validation and a typed object to pass around. That approach gives you attributes and editor completion; keleshev/schema returns plain dicts and lists, which is what the README's example asserts against. If you want the validated result to be a class with fields, this library leaves that to you.

A third option is writing the checks by hand. For two fields that is fine. The README's own example is the argument against it at scale: a list of dicts with three fields, one optional, one coerced and range-checked, is about fifteen lines of schema and would be considerably more as nested if statements with separate error messages.

Maintenance, licence and upgrade cost

The repository is not archived, and the last push was on 2026-06-20. The most recent release listed is v0.7.6 from 2024-03-26, preceded by v0.7.5 in 2021 and v0.7.3 in 2020. That gap between the last push and the last release is worth noting if you depend on tagged versions: recent commits have not been cut into a release.

The README states that the project follows semantic versioning, which is the main upgrade signal you have. Within the 0.7.x line, patches should be safe. The 0.x major number is the caution: semantic versioning permits breaking changes on a 0.x minor bump, and setup.py still classifies the project as Development Status 3 - Alpha. Pin the version you test against rather than tracking the latest.

The licence is MIT, declared in setup.py and shipped as LICENSE-MIT in the repository root. MIT is permissive: it allows use, modification and redistribution with the copyright notice and permission notice retained. That is a statement about the licence text, not legal advice for your situation.

The upgrade surface is small. There is one package directory, one dependency line in requirements.txt, and the public names used in the README (Schema, And, Use, Optional, Regex, Const, SchemaError, is_valid) are the API you would be pinning. A version bump that renames any of those is the change to watch for in the changelog.

Editorial conclusion

Adopt keleshev/schema when you already have Python data in hand (parsed JSON, YAML, form fields, argparse output) and want validation rules that read like ordinary Python expressions. Do not adopt it if you need a declarative document format that other languages can consume, or if you need to reject unknown keys by default, since the README shows no such mode. Before committing, verify three things against your own payloads: how the schema treats a missing required key, whether your Python version is still in the classifier list in setup.py, and that pip install schema resolves the version whose behaviour you tested. The library is a small, self-contained module with a MIT licence, so the cost of trying it is one file and one import.

Frequently asked questions

What is keleshev/schema in simple terms?

It is a Python library for validating Python data structures such as those obtained from config files, forms, external services or command-line parsing, converted from JSON or YAML into Python data types. You describe the expected shape with types, callables and the And, Use and Optional helpers, then call validate.

What is an example of using keleshev/schema?

The README validates a list of dicts where name is And(str, len), age is And(Use(int), lambda n: 18 <= n <= 99), and gender is Optional and lowercased before being checked against a fixed set. validate returns the converted data, and an invalid payload raises SchemaError.

How do I install keleshev/schema?

The README gives pip install schema, or you can drop the self-contained schema.py file into your project. The only declared dependency is contextlib2 for Python versions below 3.3.

Does keleshev/schema check that data is valid without raising?

Yes. The README states that schema.is_valid(data) returns True or False if you only want to check validity, while Schema.validate returns the validated data or raises SchemaError.

Can keleshev/schema convert values while validating them?

It can. Use wraps a function or type and applies it to the value, so Schema(Use(int)).validate('123') returns the integer 123. Const validates a value but keeps the original data unchanged.

Official sources

  1. Issues
  2. keleshev/schema on GitHub
  3. License: MIT
  4. README
  5. Releases
Add this badge to your README

If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.

Add this badge to your README

markdown
[![Hysen Labs](https://hysenlabs.com/badge/keleshev-schema.svg)](https://hysenlabs.com/projects/keleshev-schema)

Star history chart for your README

markdown
[![Star history](https://hysenlabs.com/chart/keleshev-schema.svg)](https://hysenlabs.com/projects/keleshev-schema)

Was this useful?