CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.

Overview

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 image image Build Status Coverage Status Gitter chat

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 [email protected] 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.

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 Date(fmt='%Y-%m-%d'):
...   return lambda v: datetime.strptime(v, fmt)
>>> 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:

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:

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

>>> 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):

>>> 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):

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

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

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

Similarly to how extra_ keys work, this behaviour can be overridden per-schema:

>>> 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):

>>> 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):

>>> 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
>>> schema({1: 2, 3: 4})
{1: 2, 3: 4}

Recursive / nested schema

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

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

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

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

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

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

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

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

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

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

s=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
s({'password':'123', 'password_again':'123'})

# raises MultipleInvalid: passwords must match
s({'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:

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

Running tests

Voluptuous is using nosetests:

$ nosetests

Other libraries and inspirations

Voluptuous is heavily inspired by Validino, and to a lesser extent, jsonvalidator and json_schema.

pytest-voluptuous is a pytest plugin that helps in using voluptuous validators in asserts.

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

Comments
  • Feature

    Feature

    Varify the maximum number of digits that are present in the number(Precision), and the maximum number of decimal places(Scale)

    :raises Invalid: If the value does not match the provided Precision and Scale.
    
    >>> s = Schema(Number(precision=6, scale=2))
    
    in progress 
    opened by nareshnootoo 18
  • Fix auto updation travis issue

    Fix auto updation travis issue

    Hey @alecthomas

    Now everything is working as desired. Please see the updated documentation over here. As you can see here Number is added, which shows that documentation is getting auto-updated.

    Thanks

    opened by tusharmakkar08 15
  • Argument validation decorator

    Argument validation decorator

    Introducing decorator that is able to validate input arguments and return value of the decorated function.

    Before calling the wrapped function, the validators specified in the decorator's argument list will be tested against the values passed at the function call.

    @validate_schema(arg1=int, arg2=int)
    def foo(arg1, arg2):
      return arg1 * arg2
    

    After calling the function with the validated arguments, schema specified in RETURNS_KEY (currently __returns__) will be applied against the output.

    @validate_schema(arg1=int, arg2=int, __returns__=int)
    def foo(arg1, arg2):
      return arg1 * arg2
    

    See more in the related test cases.

    opened by justcallmegreg 13
  • Voluptuous cannot support multi-field validation

    Voluptuous cannot support multi-field validation

    Hi @alecthomas, it looks like Voluptuous is not super active, but I thought I'd raise an architectural point with you. It seems like there's no way to write a validation which depends on the value of another field. For example, there's no way to require that a field called password and confirm_password actually match. Or that a field called size actually refers to a size that is in stock for the product referenced by product_id.

    Am I wrong, and if so, how would I do those kinds of validations? If not, are there any plans to support them?

    opened by jessedhillon 12
  • default_to() with dict doesn't appear to work

    default_to() with dict doesn't appear to work

    I was happy to find the default_to() validator to return defaults while validating a yaml document.

    Unfortunately it only seems to work in literals and lists and is not able to create dictionary keys. Is that possible? Or perhaps I'm using it wrong?

        schema1 = Schema({
            'sudo':  default_to(True),
        })
        print schema1({})
    
        schema2 = Schema([default_to(True)])
        print schema2([None])
    

    prints

    {}
    [True]
    

    I also tried giving the field as None, but then it breaks what I really want to do:

        schema1 = Schema({
            'sudo':  all(bool, default_to(True)),
        })
        print schema1({'sudo':None})
    
    voluptuous.InvalidList: expected bool for dictionary value @ data['sudo']
    
    opened by mixmastamyk 11
  • Error returned by

    Error returned by "Any" dict validator should be of the closest alternative

    Validation of Any(..) is done in the order in which the alternatives are written. When using dicts, if none of them match, the deepest error is returned. The error (that is returned in the end) is updated only when it is more nested in an alternate dict than the already existing error.

    If all dicts are of the same level, the error is from the first dict in Any(..). It would be better if Any() is made to return the error of the closest alternative. Or provide a discriminant function in the parameters used to generate error messages.

    For the example below the validation error for all three types is at the same level of the dict. The error for type A is returned as that is the first to be validated.

    from voluptuous import Schema
    
    sch = Schema({
        # this field is keyed by 'type'
        'implementation': Any({
            'type': 'A',
            'a-value': str,
        }, {
            'type': 'B',
            'b-value': int,
        }, {
            'type': 'C',
            'c-value': bool,
        })  
    })
    
    # should be OK
    sch({
        'implementation': {
            'type': 'A',
            'a-value': 'hello',}  
    })
    
    # but this one gives a very confusing error message, because Voluptuous does
    # not realize this is a (malformed) type-C implementation. Most confusingly,
    # it says the value for 'type' is not allowed, when really it is!
    # raises(
    #     er.MultipleInvalid, 
    #    'extra keys not allowed @ data['implementation']['c-value']', 
    #    'not a valid value for dictionary value @ data['implementation']['type']'
    # )
    
    sch({                                                                                                                                                                                                                         
        'implementation': {
            'type': 'C',
            'c-value': None, }
    })
    

    Probably, the error best suited here is

    expected str for dictionary value @ data['implementation']['c-value']
    

    Maybe we could return the one with shortest errors list (https://github.com/alecthomas/voluptuous/blob/master/voluptuous/schema_builder.py#L536) among all alternatives. Original discussion on BMO (reported by @djmitche)

    opened by ydidwania 10
  • add Schema.infer method

    add Schema.infer method

    This introduces the class method Schema.infer, to infer a Schema from concrete data. This will be useful for converting existing known-good data (e.g. API responses) into enforceable schemas.

    opened by dtao 10
  • Should default values fail validation?

    Should default values fail validation?

    In using voluptuous, we've come across a few cases where the following code is written:

    s = Schema({
        Optional('key', default=None): int,
    })
    

    This behaves as:

    >>> s({})
    {'key': None}
    >>> s({'key': 3})
    {'key': 3}
    

    but s({'key': None}) raises a validation error:

    voluptuous.error.MultipleInvalid: expected int for dictionary value @ data['key']
    

    On one hand, this is true as the schema specifies that the value, if provided, must be of type int.

    But, on the other hand, the developer may have expected Optional('key', default=None): int to behave as Optional('key', default=None): Any(None, int) which gives the intended behaviour:

    >>> s({})
    {'key': None}
    >>> s({'key': 3})
    {'key': 3}
    >>> s({'key': None})
    {'key': None}
    

    So the question is: if the default value on its own does not validate against the schema of the value, should that raise an error?

    I believe this issue is different from https://github.com/alecthomas/voluptuous/issues/233 as that issue is about evaluating nested default values without duplication.

    opened by svisser 10
  • Porting to new version issue

    Porting to new version issue

    Am trying to port my program from .4x to the latest. Unfortunately I was subclassing Schema to augment validate_dict. However, in the new version I no longer have access to it, since all of those functions were moved within others. What should I do?

    opened by mixmastamyk 10
  • Conflicts with Python's builtin

    Conflicts with Python's builtin

    I work @Ludia on Dynamodb-mapper projects and plan to use Voluptous as the validation layer. I love it's extremely simple syntax and ability to validate nested structures.

    Sadly, a couple of packaged validators (all and range) conflicts with Python's builtin (http://docs.python.org/library/functions.html).

    Would you accept a pull request converting the lowercasesyntaxforvalidator to CamelCaseSyntaxForValidators ?

    opened by yadutaf 10
  • More flexible schema definition

    More flexible schema definition

    We needed to be able to change schema depending on countries, and for example maybe sometimes we just want to change if a field is required or not.

    The way generally you declare voluptuous schemas doesn't make it very easy, so we just did a small function to translate from our format to voluptuous format, and we can write things like:

    MY_SCHEMA = {
        'id': Field(required=True, type=unicode),
        'choice': Field(required=True, type=V.Any('main', 'secondary')),
        'subinfo': SubSchema(SUB_SCHEMA),
    }
    

    it works quite well for us, if that's something that might be interesting to include in voluptuous let me know!

    Thanks

    opened by AndreaCrotti 9
  • No description at PyPI project page

    No description at PyPI project page

    The PyPI project page at https://pypi.org/project/voluptuous/ is missing project description. The page just says No project description provided. I believe voluptuous deserves some description, for example data validation library.

    opened by mtelka 0
  • Description argument not documented

    Description argument not documented

    The description argument for the Marker class (or any subclass) is not documented anywhere, so it's unclear what's allowed and how it affects the schema.

    opened by steverep 2
  • Ensure `sorted` in `In` works with container of data types

    Ensure `sorted` in `In` works with container of data types

    Alternative to https://github.com/alecthomas/voluptuous/pull/452

    I would prefer to keep the sorting, since that IMHO improves the error message we return, especially when utilized in user facing use cases.

    This PR nonetheless ensures we properly handle containers with data types.

    opened by spacegaier 2
  • Do not use sorted()

    Do not use sorted()

    Version 12.1 (commit https://github.com/alecthomas/voluptuous/pull/436/commits/111e1c25c6bcfbbd0da9fdb4fcc1370ffa111169) adds call of sorted function. This leads to application crash when schema container contains not comparable pair of elements. Example:

    >>> import voluptuous as vlps
    >>> s = vlps.Schema(vlps.In((str, int, float)))
    >>> d = s(42)
    Traceback (most recent call last):
      File "/usr/local/lib/python3.9/code.py", line 90, in runcode
        exec(code, self.locals)
      File "<input>", line 3, in <module>
      File ".../lib/python3.9/site-packages/voluptuous/schema_builder.py", line 272, in __call__
        return self._compiled([], data)
      File ".../lib/python3.9/site-packages/voluptuous/schema_builder.py", line 817, in validate_callable
        return schema(data)
      File ".../lib/python3.9/site-packages/voluptuous/validators.py", line 741, in __call__
        'value must be one of {}'.format(sorted(self.container)))
    TypeError: '<' not supported between instances of 'type' and 'type'
    

    This function should not be used, as it limits the possibilities of use without giving anything in return.

    opened by Avorthoren 0
  • Required keys aren't detected in Object

    Required keys aren't detected in Object

    Just leaving this here for anyone else experiencing this issue

    
    # this fails with voluptuous.error.MultipleInvalid: required key not provided @ data['test'][0]['ok']
    Schema({'test': (Object({'ok': 1}),)}, required=True)({'test': ({'ok': 1},)})
    
    # but this works
    Schema({'test': ({'ok': 1},)}, required=True)({'test': ({'ok': 1},)})
    opened by twiddli 0
Releases(0.13.1)
  • 0.13.1(Apr 7, 2022)

    Fixes:

    • #439: Ignore Enum if it is unavailable
    • #456: Fix email regex match for Python 2.7

    New:

    • #457: Enable github actions
    • #462: Convert codebase to adhere to flake8 W504 (PEP 8)
    • #459: Enable flake8 in github actions
    • #464: pytest migration + enable Python 3.10

    New Contributors:

    • @epenet Thank you for setting up the Github actions

    Full Changelog: https://github.com/alecthomas/voluptuous/compare/0.13.0...0.13.1

    Source code(tar.gz)
    Source code(zip)
  • 0.13.0(Apr 7, 2022)

  • 0.12.2(Mar 30, 2022)

  • 0.12.1(Dec 6, 2020)

    Changes:

    • #435: Extended a few tests (Required and In)
    • #425: Improve error message for In and NotIn
    • #436: Add sorted() for In and NotIn + fix tests
    • #437: Grouped Maybe tests plus added another Range test
    • #438: Extend tests for Schema with empty list or dict

    New:

    • #433: Add Python 3.9 support

    Fixes:

    • #431: Fixed typos + made spelling more consistent
    • #411: Ensure Maybe propagates error information
    • #434: Remove value enumeration when validating empty list
    Source code(tar.gz)
    Source code(zip)
  • 0.12.0(Dec 6, 2020)

    Changes:

    • n/a

    New:

    • #368: Allow a discriminant field in validators

    Fixes:

    • #420: Fixed issue with 'required' not being set properly and added test
    • #414: Handle incomparable values in Range
    • #427: Added additional tests for Range, Clamp and Length + catch TypeError exceptions
    Source code(tar.gz)
    Source code(zip)
  • 0.9.3(Aug 10, 2016)

A simple, fast, extensible python library for data validation.

Validr A simple, fast, extensible python library for data validation. Simple and readable schema 10X faster than jsonschema, 40X faster than schematic

kk 209 Sep 19, 2022
Lightweight data validation and adaptation Python library.

Valideer Lightweight data validation and adaptation library for Python. At a Glance: Supports both validation (check if a value is valid) and adaptati

Podio 258 Nov 22, 2022
Data parsing and validation using Python type hints

pydantic Data validation and settings management using Python type hinting. Fast and extensible, pydantic plays nicely with your linters/IDE/brain. De

Samuel Colvin 12.1k Jan 6, 2023
Python Data Validation for Humans™.

validators Python data validation for Humans. Python has all kinds of data validation tools, but every one of them seems to require defining a schema

Konsta Vesterinen 670 Jan 9, 2023
Typical: Fast, simple, & correct data-validation using Python 3 typing.

typical: Python's Typing Toolkit Introduction Typical is a library devoted to runtime analysis, inference, validation, and enforcement of Python types

Sean 171 Jan 2, 2023
Schema validation just got Pythonic

Schema validation just got Pythonic schema is a library for validating Python data structures, such as those obtained from config-files, forms, extern

Vladimir Keleshev 2.7k Jan 6, 2023
Schema validation for Xarray objects

xarray-schema Schema validation for Xarray installation This package is in the early stages of development. Install it from source: pip install git+gi

carbonplan 22 Oct 31, 2022
Python Data Structures for Humans™.

Schematics Python Data Structures for Humans™. About Project documentation: https://schematics.readthedocs.io/en/latest/ Schematics is a Python librar

Schematics 2.5k Dec 28, 2022
An(other) implementation of JSON Schema for Python

jsonschema jsonschema is an implementation of JSON Schema for Python. >>> from jsonschema import validate >>> # A sample schema, like what we'd get f

Julian Berman 4k Jan 4, 2023
Param: Make your Python code clearer and more reliable by declaring Parameters

Param Param is a library providing Parameters: Python attributes extended to have features such as type and range checking, dynamically generated valu

HoloViz 304 Jan 7, 2023
HTML minifier for Python frameworks (not only Django, despite the name).

django-htmlmin django-html is an HTML minifier for Python, with full support for HTML 5. It supports Django, Flask and many other Python web framework

Cobra Team 536 Dec 25, 2022
Face2webtoon - Despite its importance, there are few previous works applying I2I translation to webtoon.

Despite its importance, there are few previous works applying I2I translation to webtoon. I collected dataset from naver webtoon 연애혁명 and tried to transfer human faces to webtoon domain.

이상윤 64 Oct 19, 2022
Project created to help beginner programmers to study, despite the lack of internet!

Project created to help beginner programmers to study, despite the lack of internet!

Dev4Dev 2 Oct 25, 2021
Keras community contributions

keras-contrib : Keras community contributions Keras-contrib is deprecated. Use TensorFlow Addons. The future of Keras-contrib: We're migrating to tens

Keras 1.6k Dec 21, 2022
Patchwork is a web-based patch tracking system designed to facilitate the contribution and management of contributions to an open-source project.

Patchwork Patchwork is a patch tracking system for community-based projects. It is intended to make the patch management process easier for both the p

Patchwork 220 Nov 29, 2022
Generate a 3D Skyline in STL format and a OpenSCAD file from Gitlab contributions

Your Gitlab's contributions in a 3D Skyline gitlab-skyline is a Python command to generate a skyline figure from Gitlab contributions as Github did at

Félix Gómez 70 Dec 22, 2022
This repository is to support contributions for tools for the Project CodeNet dataset hosted in DAX

The goal of Project CodeNet is to provide the AI-for-Code research community with a large scale, diverse, and high quality curated dataset to drive innovation in AI techniques.

International Business Machines 1.2k Jan 4, 2023
Using graph_nets for pion classification and energy regression. Contributions from LLNL and LBNL

nbdev template Use this template to more easily create your nbdev project. If you are using an older version of this template, and want to upgrade to

null 3 Nov 23, 2022
GitHub Activity Generator - A script that helps you instantly generate a beautiful GitHub Contributions Graph for the last year.

GitHub Activity Generator A script that helps you instantly generate a beautiful GitHub Contributions Graph for the last year. Before ?? ?? ?? After ?

null 1 Dec 30, 2021