voluptuous


Namevoluptuous JSON
Version 0.15.1 PyPI version JSON
download
home_pagehttps://github.com/alecthomas/voluptuous
SummaryPython data validation library
upload_time2024-06-26 22:25:31
maintainerNone
docs_urlNone
authorAlec Thomas
requires_python>=3.9
licenseBSD-3-Clause
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            
# 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

[![image](https://img.shields.io/pypi/v/voluptuous.svg)](https://python.org/pypi/voluptuous)
[![image](https://img.shields.io/pypi/l/voluptuous.svg)](https://python.org/pypi/voluptuous)
[![image](https://img.shields.io/pypi/pyversions/voluptuous.svg)](https://python.org/pypi/voluptuous)
[![Test status](https://github.com/alecthomas/voluptuous/actions/workflows/tests.yml/badge.svg)](https://github.com/alecthomas/voluptuous/actions/workflows/tests.yml)
[![Coverage status](https://coveralls.io/repos/github/alecthomas/voluptuous/badge.svg?branch=master)](https://coveralls.io/github/alecthomas/voluptuous?branch=master)
[![Gitter chat](https://badges.gitter.im/alecthomas.svg)](https://gitter.im/alecthomas/Lobby)

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:

1. Simplicity.
2. Support for complex data structures.
3. Provide useful error messages.

## Contact

Voluptuous now has a mailing list! Send a mail to
[<voluptuous@librelist.com>](mailto:voluptuous@librelist.com) to subscribe. Instructions
will follow.

You can also contact me directly via [email](mailto:alec@swapoff.org) or
[Twitter](https://twitter.com/alecthomas).

To file a bug, create a [new issue](https://github.com/alecthomas/voluptuous/issues/new) on GitHub with a short example of how to replicate the issue.

## Documentation

The documentation is provided [here](http://alecthomas.github.io/voluptuous/).

## 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.](http://alecthomas.github.io/voluptuous/)

## Changelog

See [CHANGELOG.md](https://github.com/alecthomas/voluptuous/blob/master/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](https://dev.twitter.com/rest/reference/get/users/search) accepts
query URLs like:

```bash
$ 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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.

```pycon
>>> 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:

```pycon
>>> 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`:

```pycon
>>> 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:

```pycon
>>> 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`:

```pycon
>>> 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:

```pycon
>>> from datetime import datetime
>>> def Date(fmt='%Y-%m-%d'):
...   return lambda v: datetime.strptime(v, fmt)
```

```pycon
>>> schema = Schema(Date())
>>> schema('2013-03-03')
datetime.datetime(2013, 3, 3, 0, 0)
>>> try:
...   schema('2013-03')
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "not a valid value"
True
```

In addition to simply determining if a value is valid, validators may
mutate the value into a valid form. An example of this is the
`Coerce(type)` function, which returns a function that coerces its
argument to the given type:

```python
def Coerce(type, msg=None):
    """Coerce a value to a type.

    If the type constructor throws a ValueError, the value will be marked as
    Invalid.
    """
    def f(v):
        try:
            return type(v)
        except ValueError:
            raise Invalid(msg or ('expected %s' % type.__name__))
    return f
```

This example also shows a common idiom where an optional human-readable
message can be provided. This can vastly improve the usefulness of the
resulting error messages.

### Dictionaries

Each key-value pair in a schema dictionary is validated against each
key-value pair in the corresponding data dictionary:

```pycon
>>> schema = Schema({1: 'one', 2: 'two'})
>>> schema({1: 'one'})
{1: 'one'}
```

#### Extra dictionary keys

By default any additional keys in the data, not in the schema will
trigger exceptions:

```pycon
>>> schema = Schema({2: 3})
>>> try:
...   schema({1: 2, 2: 3})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "extra keys not allowed @ data[1]"
True
```

This behaviour can be altered on a per-schema basis. To allow
additional keys use
`Schema(..., extra=ALLOW_EXTRA)`:

```pycon
>>> from voluptuous import ALLOW_EXTRA
>>> schema = Schema({2: 3}, extra=ALLOW_EXTRA)
>>> schema({1: 2, 2: 3})
{1: 2, 2: 3}
```

To remove additional keys use
`Schema(..., extra=REMOVE_EXTRA)`:

```pycon
>>> from voluptuous import REMOVE_EXTRA
>>> schema = Schema({2: 3}, extra=REMOVE_EXTRA)
>>> schema({1: 2, 2: 3})
{2: 3}
```

It can also be overridden per-dictionary by using the catch-all marker
token `extra` as a key:

```pycon
>>> from voluptuous import Extra
>>> schema = Schema({1: {Extra: object}})
>>> schema({1: {'foo': 'bar'}})
{1: {'foo': 'bar'}}
```

#### Required dictionary keys

By default, keys in the schema are not required to be in the data:

```pycon
>>> schema = Schema({1: 2, 3: 4})
>>> schema({3: 4})
{3: 4}
```

Similarly to how extra\_ keys work, this behaviour can be overridden
per-schema:

```pycon
>>> schema = Schema({1: 2, 3: 4}, required=True)
>>> try:
...   schema({3: 4})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True
```

And per-key, with the marker token `Required(key)`:

```pycon
>>> schema = Schema({Required(1): 2, 3: 4})
>>> try:
...   schema({3: 4})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True
>>> schema({1: 2})
{1: 2}
```

#### Optional dictionary keys

If a schema has `required=True`, keys may be individually marked as
optional using the marker token `Optional(key)`:

```pycon
>>> from voluptuous import Optional
>>> schema = Schema({1: 2, Optional(3): 4}, required=True)
>>> try:
...   schema({})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True
>>> schema({1: 2})
{1: 2}
>>> try:
...   schema({1: 2, 4: 5})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "extra keys not allowed @ data[4]"
True
```

```pycon
>>> schema({1: 2, 3: 4})
{1: 2, 3: 4}
```

### Recursive / nested schema

You can use `voluptuous.Self` to define a nested schema:

```pycon
>>> from voluptuous import Schema, Self
>>> recursive = Schema({"more": Self, "value": int})
>>> recursive({"more": {"value": 42}, "value": 41}) == {'more': {'value': 42}, 'value': 41}
True
```

### Extending an existing Schema

Often it comes handy to have a base `Schema` that is extended with more
requirements. In that case you can use `Schema.extend` to create a new
`Schema`:

```pycon
>>> from voluptuous import Schema
>>> person = Schema({'name': str})
>>> person_with_age = person.extend({'age': int})
>>> sorted(list(person_with_age.schema.keys()))
['age', 'name']
```

The original `Schema` remains unchanged.

### Objects

Each key-value pair in a schema dictionary is validated against each
attribute-value pair in the corresponding object:

```pycon
>>> from voluptuous import Object
>>> class Structure(object):
...     def __init__(self, q=None):
...         self.q = q
...     def __repr__(self):
...         return '<Structure(q={0.q!r})>'.format(self)
...
>>> schema = Schema(Object({'q': 'one'}, cls=Structure))
>>> schema(Structure(q='one'))
<Structure(q='one')>
```

### Allow None values

To allow value to be None as well, use Any:

```pycon
>>> from voluptuous import Any

>>> schema = Schema(Any(None, int))
>>> schema(None)
>>> schema(5)
5
```

## Error reporting

Validators must throw an `Invalid` exception if invalid data is passed
to them. All other exceptions are treated as errors in the validator and
will not be caught.

Each `Invalid` exception has an associated `path` attribute representing
the path in the data structure to our currently validating value, as well
as an `error_message` attribute that contains the message of the original
exception. This is especially useful when you want to catch `Invalid`
exceptions and give some feedback to the user, for instance in the context of
an HTTP API.

```pycon
>>> def validate_email(email):
...     """Validate email."""
...     if not "@" in email:
...         raise Invalid("This email is invalid.")
...     return email
>>> schema = Schema({"email": validate_email})
>>> exc = None
>>> try:
...     schema({"email": "whatever"})
... except MultipleInvalid as e:
...     exc = e
>>> str(exc)
"This email is invalid. for dictionary value @ data['email']"
>>> exc.path
['email']
>>> exc.msg
'This email is invalid.'
>>> exc.error_message
'This email is invalid.'
```

The `path` attribute is used during error reporting, but also during matching
to determine whether an error should be reported to the user or if the next
match should be attempted. This is determined by comparing the depth of the
path where the check is, to the depth of the path where the error occurred. If
the error is more than one level deeper, it is reported.

The upshot of this is that *matching is depth-first and fail-fast*.

To illustrate this, here is an example schema:

```pycon
>>> schema = Schema([[2, 3], 6])
```

Each value in the top-level list is matched depth-first in-order. Given
input data of `[[6]]`, the inner list will match the first element of
the schema, but the literal `6` will not match any of the elements of
that list. This error will be reported back to the user immediately. No
backtracking is attempted:

```pycon
>>> try:
...   schema([[6]])
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "not a valid value @ data[0][0]"
True
```

If we pass the data `[6]`, the `6` is not a list type and so will not
recurse into the first element of the schema. Matching will continue on
to the second element in the schema, and succeed:

```pycon
>>> schema([6])
[6]
```

## Multi-field validation

Validation rules that involve multiple fields can be implemented as
custom validators. It's recommended to use `All()` to do a two-pass
validation - the first pass checking the basic structure of the data,
and only after that, the second pass applying your cross-field
validator:

```python
def passwords_must_match(passwords):
    if passwords['password'] != passwords['password_again']:
        raise Invalid('passwords must match')
    return passwords

schema = Schema(All(
    # First "pass" for field types
    {'password': str, 'password_again': str},
    # Follow up the first "pass" with your multi-field rules
    passwords_must_match
))

# valid
schema({'password': '123', 'password_again': '123'})

# raises MultipleInvalid: passwords must match
schema({'password': '123', 'password_again': 'and now for something completely different'})

```

With this structure, your multi-field validator will run with
pre-validated data from the first "pass" and so will not have to do
its own type checking on its inputs.

The flipside is that if the first "pass" of validation fails, your
cross-field validator will not run:

```python
# raises Invalid because password_again is not a string
# passwords_must_match() will not run because first-pass validation already failed
schema({'password': '123', 'password_again': 1337})
```

## Running tests

Voluptuous is using `pytest`:

```bash
$ pip install pytest
$ pytest
```

To also include a coverage report:

```bash
$ pip install pytest pytest-cov coverage>=3.0
$ pytest --cov=voluptuous voluptuous/tests/
```

## Other libraries and inspirations

Voluptuous is heavily inspired by
[Validino](http://code.google.com/p/validino/), and to a lesser extent,
[jsonvalidator](http://code.google.com/p/jsonvalidator/) and
[json\_schema](http://blog.sendapatch.se/category/json_schema.html).

[pytest-voluptuous](https://github.com/F-Secure/pytest-voluptuous) is a
[pytest](https://github.com/pytest-dev/pytest) plugin that helps in
using voluptuous validators in `assert`s.

I greatly prefer the light-weight style promoted by these libraries to
the complexity of libraries like FormEncode.


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/alecthomas/voluptuous",
    "name": "voluptuous",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": null,
    "author": "Alec Thomas",
    "author_email": "alec@swapoff.org",
    "download_url": "https://files.pythonhosted.org/packages/85/cc/fb06658c535db27316f3d356ddbfa275d0448ebd697d183982ef9791ef3f/voluptuous-0.15.1.tar.gz",
    "platform": "any",
    "description": "\n# CONTRIBUTIONS ONLY\n\n**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.\n\n**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.\n\n**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.\n\n# Voluptuous is a Python data validation library\n\n[![image](https://img.shields.io/pypi/v/voluptuous.svg)](https://python.org/pypi/voluptuous)\n[![image](https://img.shields.io/pypi/l/voluptuous.svg)](https://python.org/pypi/voluptuous)\n[![image](https://img.shields.io/pypi/pyversions/voluptuous.svg)](https://python.org/pypi/voluptuous)\n[![Test status](https://github.com/alecthomas/voluptuous/actions/workflows/tests.yml/badge.svg)](https://github.com/alecthomas/voluptuous/actions/workflows/tests.yml)\n[![Coverage status](https://coveralls.io/repos/github/alecthomas/voluptuous/badge.svg?branch=master)](https://coveralls.io/github/alecthomas/voluptuous?branch=master)\n[![Gitter chat](https://badges.gitter.im/alecthomas.svg)](https://gitter.im/alecthomas/Lobby)\n\nVoluptuous, *despite* the name, is a Python data validation library. It\nis primarily intended for validating data coming into Python as JSON,\nYAML, etc.\n\nIt has three goals:\n\n1. Simplicity.\n2. Support for complex data structures.\n3. Provide useful error messages.\n\n## Contact\n\nVoluptuous now has a mailing list! Send a mail to\n[<voluptuous@librelist.com>](mailto:voluptuous@librelist.com) to subscribe. Instructions\nwill follow.\n\nYou can also contact me directly via [email](mailto:alec@swapoff.org) or\n[Twitter](https://twitter.com/alecthomas).\n\nTo file a bug, create a [new issue](https://github.com/alecthomas/voluptuous/issues/new) on GitHub with a short example of how to replicate the issue.\n\n## Documentation\n\nThe documentation is provided [here](http://alecthomas.github.io/voluptuous/).\n\n## Contribution to Documentation\n\nDocumentation is built using `Sphinx`. You can install it by\n\n    pip install -r requirements.txt\n\nFor building `sphinx-apidoc` from scratch you need to set PYTHONPATH to `voluptuous/voluptuous` repository.\n\nThe documentation is provided [here.](http://alecthomas.github.io/voluptuous/)\n\n## Changelog\n\nSee [CHANGELOG.md](https://github.com/alecthomas/voluptuous/blob/master/CHANGELOG.md).\n\n## Why use Voluptuous over another validation library?\n\n**Validators are simple callables:**\nNo need to subclass anything, just use a function.\n\n**Errors are simple exceptions:**\nA validator can just `raise Invalid(msg)` and expect the user to get\nuseful messages.\n\n**Schemas are basic Python data structures:**\nShould your data be a dictionary of integer keys to strings?\n`{int: str}` does what you expect. List of integers, floats or\nstrings? `[int, float, str]`.\n\n**Designed from the ground up for validating more than just forms:**\nNested data structures are treated in the same way as any other\ntype. Need a list of dictionaries? `[{}]`\n\n**Consistency:**\nTypes in the schema are checked as types. Values are compared as\nvalues. Callables are called to validate. Simple.\n\n## Show me an example\n\nTwitter's [user search API](https://dev.twitter.com/rest/reference/get/users/search) accepts\nquery URLs like:\n\n```bash\n$ curl 'https://api.twitter.com/1.1/users/search.json?q=python&per_page=20&page=1'\n```\n\nTo validate this we might use a schema like:\n\n```pycon\n>>> from voluptuous import Schema\n>>> schema = Schema({\n...   'q': str,\n...   'per_page': int,\n...   'page': int,\n... })\n```\n\nThis schema very succinctly and roughly describes the data required by\nthe API, and will work fine. But it has a few problems. Firstly, it\ndoesn't fully express the constraints of the API. According to the API,\n`per_page` should be restricted to at most 20, defaulting to 5, for\nexample. To describe the semantics of the API more accurately, our\nschema will need to be more thoroughly defined:\n\n```pycon\n>>> from voluptuous import Required, All, Length, Range\n>>> schema = Schema({\n...   Required('q'): All(str, Length(min=1)),\n...   Required('per_page', default=5): All(int, Range(min=1, max=20)),\n...   'page': All(int, Range(min=0)),\n... })\n```\n\nThis schema fully enforces the interface defined in Twitter's\ndocumentation, and goes a little further for completeness.\n\n\"q\" is required:\n\n```pycon\n>>> from voluptuous import MultipleInvalid, Invalid\n>>> try:\n...   schema({})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"required key not provided @ data['q']\"\nTrue\n```\n\n...must be a string:\n\n```pycon\n>>> try:\n...   schema({'q': 123})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"expected str for dictionary value @ data['q']\"\nTrue\n```\n\n...and must be at least one character in length:\n\n```pycon\n>>> try:\n...   schema({'q': ''})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"length of value must be at least 1 for dictionary value @ data['q']\"\nTrue\n>>> schema({'q': '#topic'}) == {'q': '#topic', 'per_page': 5}\nTrue\n```\n\n\"per\\_page\" is a positive integer no greater than 20:\n\n```pycon\n>>> try:\n...   schema({'q': '#topic', 'per_page': 900})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"value must be at most 20 for dictionary value @ data['per_page']\"\nTrue\n>>> try:\n...   schema({'q': '#topic', 'per_page': -10})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"value must be at least 1 for dictionary value @ data['per_page']\"\nTrue\n```\n\n\"page\" is an integer \\>= 0:\n\n```pycon\n>>> try:\n...   schema({'q': '#topic', 'per_page': 'one'})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc)\n\"expected int for dictionary value @ data['per_page']\"\n>>> schema({'q': '#topic', 'page': 1}) == {'q': '#topic', 'page': 1, 'per_page': 5}\nTrue\n```\n\n## Defining schemas\n\nSchemas are nested data structures consisting of dictionaries, lists,\nscalars and *validators*. Each node in the input schema is pattern\nmatched against corresponding nodes in the input data.\n\n### Literals\n\nLiterals in the schema are matched using normal equality checks:\n\n```pycon\n>>> schema = Schema(1)\n>>> schema(1)\n1\n>>> schema = Schema('a string')\n>>> schema('a string')\n'a string'\n```\n\n### Types\n\nTypes in the schema are matched by checking if the corresponding value\nis an instance of the type:\n\n```pycon\n>>> schema = Schema(int)\n>>> schema(1)\n1\n>>> try:\n...   schema('one')\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"expected int\"\nTrue\n```\n\n### URLs\n\nURLs in the schema are matched by using `urlparse` library.\n\n```pycon\n>>> from voluptuous import Url\n>>> schema = Schema(Url())\n>>> schema('http://w3.org')\n'http://w3.org'\n>>> try:\n...   schema('one')\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"expected a URL\"\nTrue\n```\n\n### Lists\n\nLists in the schema are treated as a set of valid values. Each element\nin the schema list is compared to each value in the input data:\n\n```pycon\n>>> schema = Schema([1, 'a', 'string'])\n>>> schema([1])\n[1]\n>>> schema([1, 1, 1])\n[1, 1, 1]\n>>> schema(['a', 1, 'string', 1, 'string'])\n['a', 1, 'string', 1, 'string']\n```\n\nHowever, an empty list (`[]`) is treated as is. If you want to specify a list that can\ncontain anything, specify it as `list`:\n\n```pycon\n>>> schema = Schema([])\n>>> try:\n...   schema([1])\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"not a valid value @ data[1]\"\nTrue\n>>> schema([])\n[]\n>>> schema = Schema(list)\n>>> schema([])\n[]\n>>> schema([1, 2])\n[1, 2]\n```\n\n### Sets and frozensets\n\nSets and frozensets are treated as a set of valid values. Each element\nin the schema set is compared to each value in the input data:\n\n```pycon\n>>> schema = Schema({42})\n>>> schema({42}) == {42}\nTrue\n>>> try:\n...   schema({43})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"invalid value in set\"\nTrue\n>>> schema = Schema({int})\n>>> schema({1, 2, 3}) == {1, 2, 3}\nTrue\n>>> schema = Schema({int, str})\n>>> schema({1, 2, 'abc'}) == {1, 2, 'abc'}\nTrue\n>>> schema = Schema(frozenset([int]))\n>>> try:\n...   schema({3})\n...   raise AssertionError('Invalid not raised')\n... except Invalid as e:\n...   exc = e\n>>> str(exc) == 'expected a frozenset'\nTrue\n```\n\nHowever, an empty set (`set()`) is treated as is. If you want to specify a set\nthat can contain anything, specify it as `set`:\n\n```pycon\n>>> schema = Schema(set())\n>>> try:\n...   schema({1})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"invalid value in set\"\nTrue\n>>> schema(set()) == set()\nTrue\n>>> schema = Schema(set)\n>>> schema({1, 2}) == {1, 2}\nTrue\n```\n\n### Validation functions\n\nValidators are simple callables that raise an `Invalid` exception when\nthey encounter invalid data. The criteria for determining validity is\nentirely up to the implementation; it may check that a value is a valid\nusername with `pwd.getpwnam()`, it may check that a value is of a\nspecific type, and so on.\n\nThe simplest kind of validator is a Python function that raises\nValueError when its argument is invalid. Conveniently, many builtin\nPython functions have this property. Here's an example of a date\nvalidator:\n\n```pycon\n>>> from datetime import datetime\n>>> def Date(fmt='%Y-%m-%d'):\n...   return lambda v: datetime.strptime(v, fmt)\n```\n\n```pycon\n>>> schema = Schema(Date())\n>>> schema('2013-03-03')\ndatetime.datetime(2013, 3, 3, 0, 0)\n>>> try:\n...   schema('2013-03')\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"not a valid value\"\nTrue\n```\n\nIn addition to simply determining if a value is valid, validators may\nmutate the value into a valid form. An example of this is the\n`Coerce(type)` function, which returns a function that coerces its\nargument to the given type:\n\n```python\ndef Coerce(type, msg=None):\n    \"\"\"Coerce a value to a type.\n\n    If the type constructor throws a ValueError, the value will be marked as\n    Invalid.\n    \"\"\"\n    def f(v):\n        try:\n            return type(v)\n        except ValueError:\n            raise Invalid(msg or ('expected %s' % type.__name__))\n    return f\n```\n\nThis example also shows a common idiom where an optional human-readable\nmessage can be provided. This can vastly improve the usefulness of the\nresulting error messages.\n\n### Dictionaries\n\nEach key-value pair in a schema dictionary is validated against each\nkey-value pair in the corresponding data dictionary:\n\n```pycon\n>>> schema = Schema({1: 'one', 2: 'two'})\n>>> schema({1: 'one'})\n{1: 'one'}\n```\n\n#### Extra dictionary keys\n\nBy default any additional keys in the data, not in the schema will\ntrigger exceptions:\n\n```pycon\n>>> schema = Schema({2: 3})\n>>> try:\n...   schema({1: 2, 2: 3})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"extra keys not allowed @ data[1]\"\nTrue\n```\n\nThis behaviour can be altered on a per-schema basis. To allow\nadditional keys use\n`Schema(..., extra=ALLOW_EXTRA)`:\n\n```pycon\n>>> from voluptuous import ALLOW_EXTRA\n>>> schema = Schema({2: 3}, extra=ALLOW_EXTRA)\n>>> schema({1: 2, 2: 3})\n{1: 2, 2: 3}\n```\n\nTo remove additional keys use\n`Schema(..., extra=REMOVE_EXTRA)`:\n\n```pycon\n>>> from voluptuous import REMOVE_EXTRA\n>>> schema = Schema({2: 3}, extra=REMOVE_EXTRA)\n>>> schema({1: 2, 2: 3})\n{2: 3}\n```\n\nIt can also be overridden per-dictionary by using the catch-all marker\ntoken `extra` as a key:\n\n```pycon\n>>> from voluptuous import Extra\n>>> schema = Schema({1: {Extra: object}})\n>>> schema({1: {'foo': 'bar'}})\n{1: {'foo': 'bar'}}\n```\n\n#### Required dictionary keys\n\nBy default, keys in the schema are not required to be in the data:\n\n```pycon\n>>> schema = Schema({1: 2, 3: 4})\n>>> schema({3: 4})\n{3: 4}\n```\n\nSimilarly to how extra\\_ keys work, this behaviour can be overridden\nper-schema:\n\n```pycon\n>>> schema = Schema({1: 2, 3: 4}, required=True)\n>>> try:\n...   schema({3: 4})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"required key not provided @ data[1]\"\nTrue\n```\n\nAnd per-key, with the marker token `Required(key)`:\n\n```pycon\n>>> schema = Schema({Required(1): 2, 3: 4})\n>>> try:\n...   schema({3: 4})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"required key not provided @ data[1]\"\nTrue\n>>> schema({1: 2})\n{1: 2}\n```\n\n#### Optional dictionary keys\n\nIf a schema has `required=True`, keys may be individually marked as\noptional using the marker token `Optional(key)`:\n\n```pycon\n>>> from voluptuous import Optional\n>>> schema = Schema({1: 2, Optional(3): 4}, required=True)\n>>> try:\n...   schema({})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"required key not provided @ data[1]\"\nTrue\n>>> schema({1: 2})\n{1: 2}\n>>> try:\n...   schema({1: 2, 4: 5})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"extra keys not allowed @ data[4]\"\nTrue\n```\n\n```pycon\n>>> schema({1: 2, 3: 4})\n{1: 2, 3: 4}\n```\n\n### Recursive / nested schema\n\nYou can use `voluptuous.Self` to define a nested schema:\n\n```pycon\n>>> from voluptuous import Schema, Self\n>>> recursive = Schema({\"more\": Self, \"value\": int})\n>>> recursive({\"more\": {\"value\": 42}, \"value\": 41}) == {'more': {'value': 42}, 'value': 41}\nTrue\n```\n\n### Extending an existing Schema\n\nOften it comes handy to have a base `Schema` that is extended with more\nrequirements. In that case you can use `Schema.extend` to create a new\n`Schema`:\n\n```pycon\n>>> from voluptuous import Schema\n>>> person = Schema({'name': str})\n>>> person_with_age = person.extend({'age': int})\n>>> sorted(list(person_with_age.schema.keys()))\n['age', 'name']\n```\n\nThe original `Schema` remains unchanged.\n\n### Objects\n\nEach key-value pair in a schema dictionary is validated against each\nattribute-value pair in the corresponding object:\n\n```pycon\n>>> from voluptuous import Object\n>>> class Structure(object):\n...     def __init__(self, q=None):\n...         self.q = q\n...     def __repr__(self):\n...         return '<Structure(q={0.q!r})>'.format(self)\n...\n>>> schema = Schema(Object({'q': 'one'}, cls=Structure))\n>>> schema(Structure(q='one'))\n<Structure(q='one')>\n```\n\n### Allow None values\n\nTo allow value to be None as well, use Any:\n\n```pycon\n>>> from voluptuous import Any\n\n>>> schema = Schema(Any(None, int))\n>>> schema(None)\n>>> schema(5)\n5\n```\n\n## Error reporting\n\nValidators must throw an `Invalid` exception if invalid data is passed\nto them. All other exceptions are treated as errors in the validator and\nwill not be caught.\n\nEach `Invalid` exception has an associated `path` attribute representing\nthe path in the data structure to our currently validating value, as well\nas an `error_message` attribute that contains the message of the original\nexception. This is especially useful when you want to catch `Invalid`\nexceptions and give some feedback to the user, for instance in the context of\nan HTTP API.\n\n```pycon\n>>> def validate_email(email):\n...     \"\"\"Validate email.\"\"\"\n...     if not \"@\" in email:\n...         raise Invalid(\"This email is invalid.\")\n...     return email\n>>> schema = Schema({\"email\": validate_email})\n>>> exc = None\n>>> try:\n...     schema({\"email\": \"whatever\"})\n... except MultipleInvalid as e:\n...     exc = e\n>>> str(exc)\n\"This email is invalid. for dictionary value @ data['email']\"\n>>> exc.path\n['email']\n>>> exc.msg\n'This email is invalid.'\n>>> exc.error_message\n'This email is invalid.'\n```\n\nThe `path` attribute is used during error reporting, but also during matching\nto determine whether an error should be reported to the user or if the next\nmatch should be attempted. This is determined by comparing the depth of the\npath where the check is, to the depth of the path where the error occurred. If\nthe error is more than one level deeper, it is reported.\n\nThe upshot of this is that *matching is depth-first and fail-fast*.\n\nTo illustrate this, here is an example schema:\n\n```pycon\n>>> schema = Schema([[2, 3], 6])\n```\n\nEach value in the top-level list is matched depth-first in-order. Given\ninput data of `[[6]]`, the inner list will match the first element of\nthe schema, but the literal `6` will not match any of the elements of\nthat list. This error will be reported back to the user immediately. No\nbacktracking is attempted:\n\n```pycon\n>>> try:\n...   schema([[6]])\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n>>> str(exc) == \"not a valid value @ data[0][0]\"\nTrue\n```\n\nIf we pass the data `[6]`, the `6` is not a list type and so will not\nrecurse into the first element of the schema. Matching will continue on\nto the second element in the schema, and succeed:\n\n```pycon\n>>> schema([6])\n[6]\n```\n\n## Multi-field validation\n\nValidation rules that involve multiple fields can be implemented as\ncustom validators. It's recommended to use `All()` to do a two-pass\nvalidation - the first pass checking the basic structure of the data,\nand only after that, the second pass applying your cross-field\nvalidator:\n\n```python\ndef passwords_must_match(passwords):\n    if passwords['password'] != passwords['password_again']:\n        raise Invalid('passwords must match')\n    return passwords\n\nschema = Schema(All(\n    # First \"pass\" for field types\n    {'password': str, 'password_again': str},\n    # Follow up the first \"pass\" with your multi-field rules\n    passwords_must_match\n))\n\n# valid\nschema({'password': '123', 'password_again': '123'})\n\n# raises MultipleInvalid: passwords must match\nschema({'password': '123', 'password_again': 'and now for something completely different'})\n\n```\n\nWith this structure, your multi-field validator will run with\npre-validated data from the first \"pass\" and so will not have to do\nits own type checking on its inputs.\n\nThe flipside is that if the first \"pass\" of validation fails, your\ncross-field validator will not run:\n\n```python\n# raises Invalid because password_again is not a string\n# passwords_must_match() will not run because first-pass validation already failed\nschema({'password': '123', 'password_again': 1337})\n```\n\n## Running tests\n\nVoluptuous is using `pytest`:\n\n```bash\n$ pip install pytest\n$ pytest\n```\n\nTo also include a coverage report:\n\n```bash\n$ pip install pytest pytest-cov coverage>=3.0\n$ pytest --cov=voluptuous voluptuous/tests/\n```\n\n## Other libraries and inspirations\n\nVoluptuous is heavily inspired by\n[Validino](http://code.google.com/p/validino/), and to a lesser extent,\n[jsonvalidator](http://code.google.com/p/jsonvalidator/) and\n[json\\_schema](http://blog.sendapatch.se/category/json_schema.html).\n\n[pytest-voluptuous](https://github.com/F-Secure/pytest-voluptuous) is a\n[pytest](https://github.com/pytest-dev/pytest) plugin that helps in\nusing voluptuous validators in `assert`s.\n\nI greatly prefer the light-weight style promoted by these libraries to\nthe complexity of libraries like FormEncode.\n\n",
    "bugtrack_url": null,
    "license": "BSD-3-Clause",
    "summary": "Python data validation library",
    "version": "0.15.1",
    "project_urls": {
        "Download": "https://pypi.python.org/pypi/voluptuous",
        "Homepage": "https://github.com/alecthomas/voluptuous"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "85ccfb06658c535db27316f3d356ddbfa275d0448ebd697d183982ef9791ef3f",
                "md5": "468bffc9aa2048420a925d1341d650f1",
                "sha256": "4ba7f38f624379ecd02666e87e99cb24b6f5997a28258d3302c761d1a2c35d00"
            },
            "downloads": -1,
            "filename": "voluptuous-0.15.1.tar.gz",
            "has_sig": false,
            "md5_digest": "468bffc9aa2048420a925d1341d650f1",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 51347,
            "upload_time": "2024-06-26T22:25:31",
            "upload_time_iso_8601": "2024-06-26T22:25:31.745891Z",
            "url": "https://files.pythonhosted.org/packages/85/cc/fb06658c535db27316f3d356ddbfa275d0448ebd697d183982ef9791ef3f/voluptuous-0.15.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-26 22:25:31",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "alecthomas",
    "github_project": "voluptuous",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "tox": true,
    "lcname": "voluptuous"
}
        
Elapsed time: 0.35136s