{"id":13469353,"url":"https://github.com/alecthomas/voluptuous","last_synced_at":"2025-05-13T16:11:38.464Z","repository":{"id":41984028,"uuid":"776374","full_name":"alecthomas/voluptuous","owner":"alecthomas","description":"CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.","archived":false,"fork":false,"pushed_at":"2024-08-17T13:25:42.000Z","size":2532,"stargazers_count":1831,"open_issues_count":41,"forks_count":216,"subscribers_count":34,"default_branch":"master","last_synced_at":"2025-04-23T20:57:38.277Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://pypi.org/project/voluptuous","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alecthomas.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"COPYING","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2010-07-15T09:55:10.000Z","updated_at":"2025-04-14T15:21:29.000Z","dependencies_parsed_at":"2023-12-12T22:39:22.288Z","dependency_job_id":"d37355c6-3e80-4987-85c8-ed702b7eed83","html_url":"https://github.com/alecthomas/voluptuous","commit_stats":{"total_commits":370,"total_committers":105,"mean_commits":"3.5238095238095237","dds":0.7513513513513513,"last_synced_commit":"66df7bef3790af39b330832f0dc3d0be742c8171"},"previous_names":[],"tags_count":43,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fvoluptuous","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fvoluptuous/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fvoluptuous/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fvoluptuous/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alecthomas","download_url":"https://codeload.github.com/alecthomas/voluptuous/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250514767,"owners_count":21443208,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T15:01:35.531Z","updated_at":"2025-04-23T20:58:16.411Z","avatar_url":"https://github.com/alecthomas.png","language":"Python","readme":"\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[\u003cvoluptuous@librelist.com\u003e](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\u0026per_page=20\u0026page=1'\n```\n\nTo validate this we might use a schema like:\n\n```pycon\n\u003e\u003e\u003e from voluptuous import Schema\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import Required, All, Length, Range\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import MultipleInvalid, Invalid\n\u003e\u003e\u003e try:\n...   schema({})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"required key not provided @ data['q']\"\nTrue\n```\n\n...must be a string:\n\n```pycon\n\u003e\u003e\u003e try:\n...   schema({'q': 123})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e 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\u003e\u003e\u003e try:\n...   schema({'q': ''})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"length of value must be at least 1 for dictionary value @ data['q']\"\nTrue\n\u003e\u003e\u003e 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\u003e\u003e\u003e try:\n...   schema({'q': '#topic', 'per_page': 900})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"value must be at most 20 for dictionary value @ data['per_page']\"\nTrue\n\u003e\u003e\u003e try:\n...   schema({'q': '#topic', 'per_page': -10})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"value must be at least 1 for dictionary value @ data['per_page']\"\nTrue\n```\n\n\"page\" is an integer \\\u003e= 0:\n\n```pycon\n\u003e\u003e\u003e try:\n...   schema({'q': '#topic', 'per_page': 'one'})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc)\n\"expected int for dictionary value @ data['per_page']\"\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema(1)\n\u003e\u003e\u003e schema(1)\n1\n\u003e\u003e\u003e schema = Schema('a string')\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema(int)\n\u003e\u003e\u003e schema(1)\n1\n\u003e\u003e\u003e try:\n...   schema('one')\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"expected int\"\nTrue\n```\n\n### URLs\n\nURLs in the schema are matched by using `urlparse` library.\n\n```pycon\n\u003e\u003e\u003e from voluptuous import Url\n\u003e\u003e\u003e schema = Schema(Url())\n\u003e\u003e\u003e schema('http://w3.org')\n'http://w3.org'\n\u003e\u003e\u003e try:\n...   schema('one')\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema([1, 'a', 'string'])\n\u003e\u003e\u003e schema([1])\n[1]\n\u003e\u003e\u003e schema([1, 1, 1])\n[1, 1, 1]\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema([])\n\u003e\u003e\u003e try:\n...   schema([1])\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"not a valid value @ data[1]\"\nTrue\n\u003e\u003e\u003e schema([])\n[]\n\u003e\u003e\u003e schema = Schema(list)\n\u003e\u003e\u003e schema([])\n[]\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema({42})\n\u003e\u003e\u003e schema({42}) == {42}\nTrue\n\u003e\u003e\u003e try:\n...   schema({43})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"invalid value in set\"\nTrue\n\u003e\u003e\u003e schema = Schema({int})\n\u003e\u003e\u003e schema({1, 2, 3}) == {1, 2, 3}\nTrue\n\u003e\u003e\u003e schema = Schema({int, str})\n\u003e\u003e\u003e schema({1, 2, 'abc'}) == {1, 2, 'abc'}\nTrue\n\u003e\u003e\u003e schema = Schema(frozenset([int]))\n\u003e\u003e\u003e try:\n...   schema({3})\n...   raise AssertionError('Invalid not raised')\n... except Invalid as e:\n...   exc = e\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema(set())\n\u003e\u003e\u003e try:\n...   schema({1})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"invalid value in set\"\nTrue\n\u003e\u003e\u003e schema(set()) == set()\nTrue\n\u003e\u003e\u003e schema = Schema(set)\n\u003e\u003e\u003e 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\u003e\u003e\u003e from datetime import datetime\n\u003e\u003e\u003e def Date(fmt='%Y-%m-%d'):\n...   return lambda v: datetime.strptime(v, fmt)\n```\n\n```pycon\n\u003e\u003e\u003e schema = Schema(Date())\n\u003e\u003e\u003e schema('2013-03-03')\ndatetime.datetime(2013, 3, 3, 0, 0)\n\u003e\u003e\u003e try:\n...   schema('2013-03')\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema({1: 'one', 2: 'two'})\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema({2: 3})\n\u003e\u003e\u003e try:\n...   schema({1: 2, 2: 3})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import ALLOW_EXTRA\n\u003e\u003e\u003e schema = Schema({2: 3}, extra=ALLOW_EXTRA)\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import REMOVE_EXTRA\n\u003e\u003e\u003e schema = Schema({2: 3}, extra=REMOVE_EXTRA)\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import Extra\n\u003e\u003e\u003e schema = Schema({1: {Extra: object}})\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema({1: 2, 3: 4})\n\u003e\u003e\u003e 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\u003e\u003e\u003e schema = Schema({1: 2, 3: 4}, required=True)\n\u003e\u003e\u003e try:\n...   schema({3: 4})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"required key not provided @ data[1]\"\nTrue\n```\n\nAnd per-key, with the marker token `Required(key)`:\n\n```pycon\n\u003e\u003e\u003e schema = Schema({Required(1): 2, 3: 4})\n\u003e\u003e\u003e try:\n...   schema({3: 4})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"required key not provided @ data[1]\"\nTrue\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import Optional\n\u003e\u003e\u003e schema = Schema({1: 2, Optional(3): 4}, required=True)\n\u003e\u003e\u003e try:\n...   schema({})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"required key not provided @ data[1]\"\nTrue\n\u003e\u003e\u003e schema({1: 2})\n{1: 2}\n\u003e\u003e\u003e try:\n...   schema({1: 2, 4: 5})\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e str(exc) == \"extra keys not allowed @ data[4]\"\nTrue\n```\n\n```pycon\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import Schema, Self\n\u003e\u003e\u003e recursive = Schema({\"more\": Self, \"value\": int})\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import Schema\n\u003e\u003e\u003e person = Schema({'name': str})\n\u003e\u003e\u003e person_with_age = person.extend({'age': int})\n\u003e\u003e\u003e 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\u003e\u003e\u003e from voluptuous import Object\n\u003e\u003e\u003e class Structure(object):\n...     def __init__(self, q=None):\n...         self.q = q\n...     def __repr__(self):\n...         return '\u003cStructure(q={0.q!r})\u003e'.format(self)\n...\n\u003e\u003e\u003e schema = Schema(Object({'q': 'one'}, cls=Structure))\n\u003e\u003e\u003e schema(Structure(q='one'))\n\u003cStructure(q='one')\u003e\n```\n\n### Allow None values\n\nTo allow value to be None as well, use Any:\n\n```pycon\n\u003e\u003e\u003e from voluptuous import Any\n\n\u003e\u003e\u003e schema = Schema(Any(None, int))\n\u003e\u003e\u003e schema(None)\n\u003e\u003e\u003e 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\u003e\u003e\u003e def validate_email(email):\n...     \"\"\"Validate email.\"\"\"\n...     if not \"@\" in email:\n...         raise Invalid(\"This email is invalid.\")\n...     return email\n\u003e\u003e\u003e schema = Schema({\"email\": validate_email})\n\u003e\u003e\u003e exc = None\n\u003e\u003e\u003e try:\n...     schema({\"email\": \"whatever\"})\n... except MultipleInvalid as e:\n...     exc = e\n\u003e\u003e\u003e str(exc)\n\"This email is invalid. for dictionary value @ data['email']\"\n\u003e\u003e\u003e exc.path\n['email']\n\u003e\u003e\u003e exc.msg\n'This email is invalid.'\n\u003e\u003e\u003e 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\u003e\u003e\u003e 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\u003e\u003e\u003e try:\n...   schema([[6]])\n...   raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n...   exc = e\n\u003e\u003e\u003e 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\u003e\u003e\u003e 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\u003e=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","funding_links":[],"categories":["Data Validation","Python","资源列表","Libraries in Python","数据验证","Data validation","Libraries (Python)","Data Validation [🔝](#readme)","Awesome Python"],"sub_categories":["数据验证","Data Validation"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fvoluptuous","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falecthomas%2Fvoluptuous","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fvoluptuous/lists"}