Voluptuous
CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
Install / Use
/learn @alecthomas/VoluptuousREADME
CONTRIBUTIONS ONLY
What does this mean? I do not have time to fix issues myself. The only way fixes or new features will be added is by people submitting PRs.
Current status: Voluptuous is largely feature stable. There hasn't been a need to add new features in a while, but there are some bugs that should be fixed.
Why? I no longer use Voluptuous personally (in fact I no longer regularly write Python code). Rather than leave the project in a limbo of people filing issues and wondering why they're not being worked on, I believe this notice will more clearly set expectations.
Voluptuous is a Python data validation library
Voluptuous, despite the name, is a Python data validation library. It is primarily intended for validating data coming into Python as JSON, YAML, etc.
It has three goals:
- Simplicity.
- Support for complex data structures.
- Provide useful error messages.
Contact
Voluptuous now has a mailing list! Send a mail to voluptuous@librelist.com to subscribe. Instructions will follow.
You can also contact me directly via email or Twitter.
To file a bug, create a new issue on GitHub with a short example of how to replicate the issue.
Documentation
The documentation is provided here.
Contribution to Documentation
Documentation is built using Sphinx. You can install it by
pip install -r requirements.txt
For building sphinx-apidoc from scratch you need to set PYTHONPATH to voluptuous/voluptuous repository.
The documentation is provided here.
Changelog
See CHANGELOG.md.
Why use Voluptuous over another validation library?
Validators are simple callables: No need to subclass anything, just use a function.
Errors are simple exceptions:
A validator can just raise Invalid(msg) and expect the user to get
useful messages.
Schemas are basic Python data structures:
Should your data be a dictionary of integer keys to strings?
{int: str} does what you expect. List of integers, floats or
strings? [int, float, str].
Designed from the ground up for validating more than just forms:
Nested data structures are treated in the same way as any other
type. Need a list of dictionaries? [{}]
Consistency: Types in the schema are checked as types. Values are compared as values. Callables are called to validate. Simple.
Show me an example
Twitter's user search API accepts query URLs like:
$ curl 'https://api.twitter.com/1.1/users/search.json?q=python&per_page=20&page=1'
To validate this we might use a schema like:
>>> from voluptuous import Schema
>>> schema = Schema({
... 'q': str,
... 'per_page': int,
... 'page': int,
... })
This schema very succinctly and roughly describes the data required by
the API, and will work fine. But it has a few problems. Firstly, it
doesn't fully express the constraints of the API. According to the API,
per_page should be restricted to at most 20, defaulting to 5, for
example. To describe the semantics of the API more accurately, our
schema will need to be more thoroughly defined:
>>> from voluptuous import Required, All, Length, Range
>>> schema = Schema({
... Required('q'): All(str, Length(min=1)),
... Required('per_page', default=5): All(int, Range(min=1, max=20)),
... 'page': All(int, Range(min=0)),
... })
This schema fully enforces the interface defined in Twitter's documentation, and goes a little further for completeness.
"q" is required:
>>> from voluptuous import MultipleInvalid, Invalid
>>> try:
... schema({})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "required key not provided @ data['q']"
True
...must be a string:
>>> try:
... schema({'q': 123})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "expected str for dictionary value @ data['q']"
True
...and must be at least one character in length:
>>> try:
... schema({'q': ''})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "length of value must be at least 1 for dictionary value @ data['q']"
True
>>> schema({'q': '#topic'}) == {'q': '#topic', 'per_page': 5}
True
"per_page" is a positive integer no greater than 20:
>>> try:
... schema({'q': '#topic', 'per_page': 900})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "value must be at most 20 for dictionary value @ data['per_page']"
True
>>> try:
... schema({'q': '#topic', 'per_page': -10})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "value must be at least 1 for dictionary value @ data['per_page']"
True
"page" is an integer >= 0:
>>> try:
... schema({'q': '#topic', 'per_page': 'one'})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc)
"expected int for dictionary value @ data['per_page']"
>>> schema({'q': '#topic', 'page': 1}) == {'q': '#topic', 'page': 1, 'per_page': 5}
True
Defining schemas
Schemas are nested data structures consisting of dictionaries, lists, scalars and validators. Each node in the input schema is pattern matched against corresponding nodes in the input data.
Literals
Literals in the schema are matched using normal equality checks:
>>> schema = Schema(1)
>>> schema(1)
1
>>> schema = Schema('a string')
>>> schema('a string')
'a string'
Types
Types in the schema are matched by checking if the corresponding value is an instance of the type:
>>> schema = Schema(int)
>>> schema(1)
1
>>> try:
... schema('one')
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "expected int"
True
URLs
URLs in the schema are matched by using urlparse library.
>>> from voluptuous import Url
>>> schema = Schema(Url())
>>> schema('http://w3.org')
'http://w3.org'
>>> try:
... schema('one')
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "expected a URL"
True
Lists
Lists in the schema are treated as a set of valid values. Each element in the schema list is compared to each value in the input data:
>>> schema = Schema([1, 'a', 'string'])
>>> schema([1])
[1]
>>> schema([1, 1, 1])
[1, 1, 1]
>>> schema(['a', 1, 'string', 1, 'string'])
['a', 1, 'string', 1, 'string']
However, an empty list ([]) is treated as is. If you want to specify a list that can
contain anything, specify it as list:
>>> schema = Schema([])
>>> try:
... schema([1])
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "not a valid value @ data[1]"
True
>>> schema([])
[]
>>> schema = Schema(list)
>>> schema([])
[]
>>> schema([1, 2])
[1, 2]
Sets and frozensets
Sets and frozensets are treated as a set of valid values. Each element in the schema set is compared to each value in the input data:
>>> schema = Schema({42})
>>> schema({42}) == {42}
True
>>> try:
... schema({43})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "invalid value in set"
True
>>> schema = Schema({int})
>>> schema({1, 2, 3}) == {1, 2, 3}
True
>>> schema = Schema({int, str})
>>> schema({1, 2, 'abc'}) == {1, 2, 'abc'}
True
>>> schema = Schema(frozenset([int]))
>>> try:
... schema({3})
... raise AssertionError('Invalid not raised')
... except Invalid as e:
... exc = e
>>> str(exc) == 'expected a frozenset'
True
However, an empty set (set()) is treated as is. If you want to specify a set
that can contain anything, specify it as set:
>>> schema = Schema(set())
>>> try:
... schema({1})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "invalid value in set"
True
>>> schema(set()) == set()
True
>>> schema = Schema(set)
>>> schema({1, 2}) == {1, 2}
True
Validation functions
Validators are simple callables that raise an Invalid exception when
they encounter invalid data. The criteria for determining validity is
entirely up to the implementation; it may check that a value is a valid
username with pwd.getpwnam(), it may check that a value is of a
specific type, and so on.
The simplest kind of validator is a Python function that raises ValueError when its argument is invalid. Conveniently, many builtin Python functions have this property. Here's an example of a date validator:
>>> from datetime import datetime
>>> def Dat
Related Skills
node-connect
332.9kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
81.9kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
332.9kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
81.9kCommit, push, and open a PR
