Debian Codegraph @

third_party/python/voluptuous/voluptuous-0.12.1.dist-info/METADATA

raw
1 Metadata-Version: 2.1
2 Name: voluptuous
3 Version: 0.12.1
4 Summary: UNKNOWN
5 Home-page: https://github.com/alecthomas/voluptuous
6 Author: Alec Thomas
7 Author-email: [email protected]
8 License: BSD
9 Download-URL: https://pypi.python.org/pypi/voluptuous
10 Platform: any
11 Classifier: Development Status :: 5 - Production/Stable
12 Classifier: Intended Audience :: Developers
13 Classifier: License :: OSI Approved :: BSD License
14 Classifier: Operating System :: OS Independent
15 Classifier: Programming Language :: Python :: 2
16 Classifier: Programming Language :: Python :: 2.7
17 Classifier: Programming Language :: Python :: 3
18 Classifier: Programming Language :: Python :: 3.6
19 Classifier: Programming Language :: Python :: 3.7
20 Classifier: Programming Language :: Python :: 3.8
21 Classifier: Programming Language :: Python :: 3.9
22 Description-Content-Type: text/markdown
23
24
25 # CONTRIBUTIONS ONLY
26
27 **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.
28
29 **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.
30
31 **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.
32
33 # Voluptuous is a Python data validation library
34
35 [![image](https://img.shields.io/pypi/v/voluptuous.svg)](https://python.org/pypi/voluptuous)
36 [![image](https://img.shields.io/pypi/l/voluptuous.svg)](https://python.org/pypi/voluptuous)
37 [![image](https://img.shields.io/pypi/pyversions/voluptuous.svg)](https://python.org/pypi/voluptuous)
38 [![Build Status](https://travis-ci.org/alecthomas/voluptuous.svg)](https://travis-ci.org/alecthomas/voluptuous)
39 [![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)
40
41 Voluptuous, *despite* the name, is a Python data validation library. It
42 is primarily intended for validating data coming into Python as JSON,
43 YAML, etc.
44
45 It has three goals:
46
47 1. Simplicity.
48 2. Support for complex data structures.
49 3. Provide useful error messages.
50
51 ## Contact
52
53 Voluptuous now has a mailing list! Send a mail to
54 [<[email protected]>](mailto:[email protected]) to subscribe. Instructions
55 will follow.
56
57 You can also contact me directly via [email](mailto:[email protected]) or
58 [Twitter](https://twitter.com/alecthomas).
59
60 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.
61
62 ## Documentation
63
64 The documentation is provided [here](http://alecthomas.github.io/voluptuous/).
65
66 ## Changelog
67
68 See [CHANGELOG.md](https://github.com/alecthomas/voluptuous/blob/master/CHANGELOG.md).
69
70 ## Why use Voluptuous over another validation library?
71
72 **Validators are simple callables:**
73 No need to subclass anything, just use a function.
74
75 **Errors are simple exceptions:**
76 A validator can just `raise Invalid(msg)` and expect the user to get
77 useful messages.
78
79 **Schemas are basic Python data structures:**
80 Should your data be a dictionary of integer keys to strings?
81 `{int: str}` does what you expect. List of integers, floats or
82 strings? `[int, float, str]`.
83
84 **Designed from the ground up for validating more than just forms:**
85 Nested data structures are treated in the same way as any other
86 type. Need a list of dictionaries? `[{}]`
87
88 **Consistency:**
89 Types in the schema are checked as types. Values are compared as
90 values. Callables are called to validate. Simple.
91
92 ## Show me an example
93
94 Twitter's [user search API](https://dev.twitter.com/rest/reference/get/users/search) accepts
95 query URLs like:
96
97 ```
98 $ curl 'https://api.twitter.com/1.1/users/search.json?q=python&per_page=20&page=1'
99 ```
100
101 To validate this we might use a schema like:
102
103 ```pycon
104 >>> from voluptuous import Schema
105 >>> schema = Schema({
106 ... 'q': str,
107 ... 'per_page': int,
108 ... 'page': int,
109 ... })
110
111 ```
112
113 This schema very succinctly and roughly describes the data required by
114 the API, and will work fine. But it has a few problems. Firstly, it
115 doesn't fully express the constraints of the API. According to the API,
116 `per_page` should be restricted to at most 20, defaulting to 5, for
117 example. To describe the semantics of the API more accurately, our
118 schema will need to be more thoroughly defined:
119
120 ```pycon
121 >>> from voluptuous import Required, All, Length, Range
122 >>> schema = Schema({
123 ... Required('q'): All(str, Length(min=1)),
124 ... Required('per_page', default=5): All(int, Range(min=1, max=20)),
125 ... 'page': All(int, Range(min=0)),
126 ... })
127
128 ```
129
130 This schema fully enforces the interface defined in Twitter's
131 documentation, and goes a little further for completeness.
132
133 "q" is required:
134
135 ```pycon
136 >>> from voluptuous import MultipleInvalid, Invalid
137 >>> try:
138 ... schema({})
139 ... raise AssertionError('MultipleInvalid not raised')
140 ... except MultipleInvalid as e:
141 ... exc = e
142 >>> str(exc) == "required key not provided @ data['q']"
143 True
144
145 ```
146
147 ...must be a string:
148
149 ```pycon
150 >>> try:
151 ... schema({'q': 123})
152 ... raise AssertionError('MultipleInvalid not raised')
153 ... except MultipleInvalid as e:
154 ... exc = e
155 >>> str(exc) == "expected str for dictionary value @ data['q']"
156 True
157
158 ```
159
160 ...and must be at least one character in length:
161
162 ```pycon
163 >>> try:
164 ... schema({'q': ''})
165 ... raise AssertionError('MultipleInvalid not raised')
166 ... except MultipleInvalid as e:
167 ... exc = e
168 >>> str(exc) == "length of value must be at least 1 for dictionary value @ data['q']"
169 True
170 >>> schema({'q': '#topic'}) == {'q': '#topic', 'per_page': 5}
171 True
172
173 ```
174
175 "per\_page" is a positive integer no greater than 20:
176
177 ```pycon
178 >>> try:
179 ... schema({'q': '#topic', 'per_page': 900})
180 ... raise AssertionError('MultipleInvalid not raised')
181 ... except MultipleInvalid as e:
182 ... exc = e
183 >>> str(exc) == "value must be at most 20 for dictionary value @ data['per_page']"
184 True
185 >>> try:
186 ... schema({'q': '#topic', 'per_page': -10})
187 ... raise AssertionError('MultipleInvalid not raised')
188 ... except MultipleInvalid as e:
189 ... exc = e
190 >>> str(exc) == "value must be at least 1 for dictionary value @ data['per_page']"
191 True
192
193 ```
194
195 "page" is an integer \>= 0:
196
197 ```pycon
198 >>> try:
199 ... schema({'q': '#topic', 'per_page': 'one'})
200 ... raise AssertionError('MultipleInvalid not raised')
201 ... except MultipleInvalid as e:
202 ... exc = e
203 >>> str(exc)
204 "expected int for dictionary value @ data['per_page']"
205 >>> schema({'q': '#topic', 'page': 1}) == {'q': '#topic', 'page': 1, 'per_page': 5}
206 True
207
208 ```
209
210 ## Defining schemas
211
212 Schemas are nested data structures consisting of dictionaries, lists,
213 scalars and *validators*. Each node in the input schema is pattern
214 matched against corresponding nodes in the input data.
215
216 ### Literals
217
218 Literals in the schema are matched using normal equality checks:
219
220 ```pycon
221 >>> schema = Schema(1)
222 >>> schema(1)
223 1
224 >>> schema = Schema('a string')
225 >>> schema('a string')
226 'a string'
227
228 ```
229
230 ### Types
231
232 Types in the schema are matched by checking if the corresponding value
233 is an instance of the type:
234
235 ```pycon
236 >>> schema = Schema(int)
237 >>> schema(1)
238 1
239 >>> try:
240 ... schema('one')
241 ... raise AssertionError('MultipleInvalid not raised')
242 ... except MultipleInvalid as e:
243 ... exc = e
244 >>> str(exc) == "expected int"
245 True
246
247 ```
248
249 ### URLs
250
251 URLs in the schema are matched by using `urlparse` library.
252
253 ```pycon
254 >>> from voluptuous import Url
255 >>> schema = Schema(Url())
256 >>> schema('http://w3.org')
257 'http://w3.org'
258 >>> try:
259 ... schema('one')
260 ... raise AssertionError('MultipleInvalid not raised')
261 ... except MultipleInvalid as e:
262 ... exc = e
263 >>> str(exc) == "expected a URL"
264 True
265
266 ```
267
268 ### Lists
269
270 Lists in the schema are treated as a set of valid values. Each element
271 in the schema list is compared to each value in the input data:
272
273 ```pycon
274 >>> schema = Schema([1, 'a', 'string'])
275 >>> schema([1])
276 [1]
277 >>> schema([1, 1, 1])
278 [1, 1, 1]
279 >>> schema(['a', 1, 'string', 1, 'string'])
280 ['a', 1, 'string', 1, 'string']
281
282 ```
283
284 However, an empty list (`[]`) is treated as is. If you want to specify a list that can
285 contain anything, specify it as `list`:
286
287 ```pycon
288 >>> schema = Schema([])
289 >>> try:
290 ... schema([1])
291 ... raise AssertionError('MultipleInvalid not raised')
292 ... except MultipleInvalid as e:
293 ... exc = e
294 >>> str(exc) == "not a valid value @ data[1]"
295 True
296 >>> schema([])
297 []
298 >>> schema = Schema(list)
299 >>> schema([])
300 []
301 >>> schema([1, 2])
302 [1, 2]
303
304 ```
305
306 ### Sets and frozensets
307
308 Sets and frozensets are treated as a set of valid values. Each element
309 in the schema set is compared to each value in the input data:
310
311 ```pycon
312 >>> schema = Schema({42})
313 >>> schema({42}) == {42}
314 True
315 >>> try:
316 ... schema({43})
317 ... raise AssertionError('MultipleInvalid not raised')
318 ... except MultipleInvalid as e:
319 ... exc = e
320 >>> str(exc) == "invalid value in set"
321 True
322 >>> schema = Schema({int})
323 >>> schema({1, 2, 3}) == {1, 2, 3}
324 True
325 >>> schema = Schema({int, str})
326 >>> schema({1, 2, 'abc'}) == {1, 2, 'abc'}
327 True
328 >>> schema = Schema(frozenset([int]))
329 >>> try:
330 ... schema({3})
331 ... raise AssertionError('Invalid not raised')
332 ... except Invalid as e:
333 ... exc = e
334 >>> str(exc) == 'expected a frozenset'
335 True
336
337 ```
338
339 However, an empty set (`set()`) is treated as is. If you want to specify a set
340 that can contain anything, specify it as `set`:
341
342 ```pycon
343 >>> schema = Schema(set())
344 >>> try:
345 ... schema({1})
346 ... raise AssertionError('MultipleInvalid not raised')
347 ... except MultipleInvalid as e:
348 ... exc = e
349 >>> str(exc) == "invalid value in set"
350 True
351 >>> schema(set()) == set()
352 True
353 >>> schema = Schema(set)
354 >>> schema({1, 2}) == {1, 2}
355 True
356
357 ```
358
359 ### Validation functions
360
361 Validators are simple callables that raise an `Invalid` exception when
362 they encounter invalid data. The criteria for determining validity is
363 entirely up to the implementation; it may check that a value is a valid
364 username with `pwd.getpwnam()`, it may check that a value is of a
365 specific type, and so on.
366
367 The simplest kind of validator is a Python function that raises
368 ValueError when its argument is invalid. Conveniently, many builtin
369 Python functions have this property. Here's an example of a date
370 validator:
371
372 ```pycon
373 >>> from datetime import datetime
374 >>> def Date(fmt='%Y-%m-%d'):
375 ... return lambda v: datetime.strptime(v, fmt)
376
377 ```
378
379 ```pycon
380 >>> schema = Schema(Date())
381 >>> schema('2013-03-03')
382 datetime.datetime(2013, 3, 3, 0, 0)
383 >>> try:
384 ... schema('2013-03')
385 ... raise AssertionError('MultipleInvalid not raised')
386 ... except MultipleInvalid as e:
387 ... exc = e
388 >>> str(exc) == "not a valid value"
389 True
390
391 ```
392
393 In addition to simply determining if a value is valid, validators may
394 mutate the value into a valid form. An example of this is the
395 `Coerce(type)` function, which returns a function that coerces its
396 argument to the given type:
397
398 ```python
399 def Coerce(type, msg=None):
400 """Coerce a value to a type.
401
402 If the type constructor throws a ValueError, the value will be marked as
403 Invalid.
404 """
405 def f(v):
406 try:
407 return type(v)
408 except ValueError:
409 raise Invalid(msg or ('expected %s' % type.__name__))
410 return f
411
412 ```
413
414 This example also shows a common idiom where an optional human-readable
415 message can be provided. This can vastly improve the usefulness of the
416 resulting error messages.
417
418 ### Dictionaries
419
420 Each key-value pair in a schema dictionary is validated against each
421 key-value pair in the corresponding data dictionary:
422
423 ```pycon
424 >>> schema = Schema({1: 'one', 2: 'two'})
425 >>> schema({1: 'one'})
426 {1: 'one'}
427
428 ```
429
430 #### Extra dictionary keys
431
432 By default any additional keys in the data, not in the schema will
433 trigger exceptions:
434
435 ```pycon
436 >>> schema = Schema({2: 3})
437 >>> try:
438 ... schema({1: 2, 2: 3})
439 ... raise AssertionError('MultipleInvalid not raised')
440 ... except MultipleInvalid as e:
441 ... exc = e
442 >>> str(exc) == "extra keys not allowed @ data[1]"
443 True
444
445 ```
446
447 This behaviour can be altered on a per-schema basis. To allow
448 additional keys use
449 `Schema(..., extra=ALLOW_EXTRA)`:
450
451 ```pycon
452 >>> from voluptuous import ALLOW_EXTRA
453 >>> schema = Schema({2: 3}, extra=ALLOW_EXTRA)
454 >>> schema({1: 2, 2: 3})
455 {1: 2, 2: 3}
456
457 ```
458
459 To remove additional keys use
460 `Schema(..., extra=REMOVE_EXTRA)`:
461
462 ```pycon
463 >>> from voluptuous import REMOVE_EXTRA
464 >>> schema = Schema({2: 3}, extra=REMOVE_EXTRA)
465 >>> schema({1: 2, 2: 3})
466 {2: 3}
467
468 ```
469
470 It can also be overridden per-dictionary by using the catch-all marker
471 token `extra` as a key:
472
473 ```pycon
474 >>> from voluptuous import Extra
475 >>> schema = Schema({1: {Extra: object}})
476 >>> schema({1: {'foo': 'bar'}})
477 {1: {'foo': 'bar'}}
478
479 ```
480
481 #### Required dictionary keys
482
483 By default, keys in the schema are not required to be in the data:
484
485 ```pycon
486 >>> schema = Schema({1: 2, 3: 4})
487 >>> schema({3: 4})
488 {3: 4}
489
490 ```
491
492 Similarly to how extra\_ keys work, this behaviour can be overridden
493 per-schema:
494
495 ```pycon
496 >>> schema = Schema({1: 2, 3: 4}, required=True)
497 >>> try:
498 ... schema({3: 4})
499 ... raise AssertionError('MultipleInvalid not raised')
500 ... except MultipleInvalid as e:
501 ... exc = e
502 >>> str(exc) == "required key not provided @ data[1]"
503 True
504
505 ```
506
507 And per-key, with the marker token `Required(key)`:
508
509 ```pycon
510 >>> schema = Schema({Required(1): 2, 3: 4})
511 >>> try:
512 ... schema({3: 4})
513 ... raise AssertionError('MultipleInvalid not raised')
514 ... except MultipleInvalid as e:
515 ... exc = e
516 >>> str(exc) == "required key not provided @ data[1]"
517 True
518 >>> schema({1: 2})
519 {1: 2}
520
521 ```
522
523 #### Optional dictionary keys
524
525 If a schema has `required=True`, keys may be individually marked as
526 optional using the marker token `Optional(key)`:
527
528 ```pycon
529 >>> from voluptuous import Optional
530 >>> schema = Schema({1: 2, Optional(3): 4}, required=True)
531 >>> try:
532 ... schema({})
533 ... raise AssertionError('MultipleInvalid not raised')
534 ... except MultipleInvalid as e:
535 ... exc = e
536 >>> str(exc) == "required key not provided @ data[1]"
537 True
538 >>> schema({1: 2})
539 {1: 2}
540 >>> try:
541 ... schema({1: 2, 4: 5})
542 ... raise AssertionError('MultipleInvalid not raised')
543 ... except MultipleInvalid as e:
544 ... exc = e
545 >>> str(exc) == "extra keys not allowed @ data[4]"
546 True
547
548 ```
549
550 ```pycon
551 >>> schema({1: 2, 3: 4})
552 {1: 2, 3: 4}
553
554 ```
555
556 ### Recursive / nested schema
557
558 You can use `voluptuous.Self` to define a nested schema:
559
560 ```pycon
561 >>> from voluptuous import Schema, Self
562 >>> recursive = Schema({"more": Self, "value": int})
563 >>> recursive({"more": {"value": 42}, "value": 41}) == {'more': {'value': 42}, 'value': 41}
564 True
565
566 ```
567
568 ### Extending an existing Schema
569
570 Often it comes handy to have a base `Schema` that is extended with more
571 requirements. In that case you can use `Schema.extend` to create a new
572 `Schema`:
573
574 ```pycon
575 >>> from voluptuous import Schema
576 >>> person = Schema({'name': str})
577 >>> person_with_age = person.extend({'age': int})
578 >>> sorted(list(person_with_age.schema.keys()))
579 ['age', 'name']
580
581 ```
582
583 The original `Schema` remains unchanged.
584
585 ### Objects
586
587 Each key-value pair in a schema dictionary is validated against each
588 attribute-value pair in the corresponding object:
589
590 ```pycon
591 >>> from voluptuous import Object
592 >>> class Structure(object):
593 ... def __init__(self, q=None):
594 ... self.q = q
595 ... def __repr__(self):
596 ... return '<Structure(q={0.q!r})>'.format(self)
597 ...
598 >>> schema = Schema(Object({'q': 'one'}, cls=Structure))
599 >>> schema(Structure(q='one'))
600 <Structure(q='one')>
601
602 ```
603
604 ### Allow None values
605
606 To allow value to be None as well, use Any:
607
608 ```pycon
609 >>> from voluptuous import Any
610
611 >>> schema = Schema(Any(None, int))
612 >>> schema(None)
613 >>> schema(5)
614 5
615
616 ```
617
618 ## Error reporting
619
620 Validators must throw an `Invalid` exception if invalid data is passed
621 to them. All other exceptions are treated as errors in the validator and
622 will not be caught.
623
624 Each `Invalid` exception has an associated `path` attribute representing
625 the path in the data structure to our currently validating value, as well
626 as an `error_message` attribute that contains the message of the original
627 exception. This is especially useful when you want to catch `Invalid`
628 exceptions and give some feedback to the user, for instance in the context of
629 an HTTP API.
630
631
632 ```pycon
633 >>> def validate_email(email):
634 ... """Validate email."""
635 ... if not "@" in email:
636 ... raise Invalid("This email is invalid.")
637 ... return email
638 >>> schema = Schema({"email": validate_email})
639 >>> exc = None
640 >>> try:
641 ... schema({"email": "whatever"})
642 ... except MultipleInvalid as e:
643 ... exc = e
644 >>> str(exc)
645 "This email is invalid. for dictionary value @ data['email']"
646 >>> exc.path
647 ['email']
648 >>> exc.msg
649 'This email is invalid.'
650 >>> exc.error_message
651 'This email is invalid.'
652
653 ```
654
655 The `path` attribute is used during error reporting, but also during matching
656 to determine whether an error should be reported to the user or if the next
657 match should be attempted. This is determined by comparing the depth of the
658 path where the check is, to the depth of the path where the error occurred. If
659 the error is more than one level deeper, it is reported.
660
661 The upshot of this is that *matching is depth-first and fail-fast*.
662
663 To illustrate this, here is an example schema:
664
665 ```pycon
666 >>> schema = Schema([[2, 3], 6])
667
668 ```
669
670 Each value in the top-level list is matched depth-first in-order. Given
671 input data of `[[6]]`, the inner list will match the first element of
672 the schema, but the literal `6` will not match any of the elements of
673 that list. This error will be reported back to the user immediately. No
674 backtracking is attempted:
675
676 ```pycon
677 >>> try:
678 ... schema([[6]])
679 ... raise AssertionError('MultipleInvalid not raised')
680 ... except MultipleInvalid as e:
681 ... exc = e
682 >>> str(exc) == "not a valid value @ data[0][0]"
683 True
684
685 ```
686
687 If we pass the data `[6]`, the `6` is not a list type and so will not
688 recurse into the first element of the schema. Matching will continue on
689 to the second element in the schema, and succeed:
690
691 ```pycon
692 >>> schema([6])
693 [6]
694
695 ```
696
697 ## Multi-field validation
698
699 Validation rules that involve multiple fields can be implemented as
700 custom validators. It's recommended to use `All()` to do a two-pass
701 validation - the first pass checking the basic structure of the data,
702 and only after that, the second pass applying your cross-field
703 validator:
704
705 ```python
706 def passwords_must_match(passwords):
707 if passwords['password'] != passwords['password_again']:
708 raise Invalid('passwords must match')
709 return passwords
710
711 s=Schema(All(
712 # First "pass" for field types
713 {'password':str, 'password_again':str},
714 # Follow up the first "pass" with your multi-field rules
715 passwords_must_match
716 ))
717
718 # valid
719 s({'password':'123', 'password_again':'123'})
720
721 # raises MultipleInvalid: passwords must match
722 s({'password':'123', 'password_again':'and now for something completely different'})
723
724 ```
725
726 With this structure, your multi-field validator will run with
727 pre-validated data from the first "pass" and so will not have to do
728 its own type checking on its inputs.
729
730 The flipside is that if the first "pass" of validation fails, your
731 cross-field validator will not run:
732
733 ```
734 # raises Invalid because password_again is not a string
735 # passwords_must_match() will not run because first-pass validation already failed
736 s({'password':'123', 'password_again': 1337})
737 ```
738
739 ## Running tests
740
741 Voluptuous is using nosetests:
742
743 $ nosetests
744
745
746 ## Other libraries and inspirations
747
748 Voluptuous is heavily inspired by
749 [Validino](http://code.google.com/p/validino/), and to a lesser extent,
750 [jsonvalidator](http://code.google.com/p/jsonvalidator/) and
751 [json\_schema](http://blog.sendapatch.se/category/json_schema.html).
752
753 [pytest-voluptuous](https://github.com/F-Secure/pytest-voluptuous) is a
754 [pytest](https://github.com/pytest-dev/pytest) plugin that helps in
755 using voluptuous validators in `assert`s.
756
757 I greatly prefer the light-weight style promoted by these libraries to
758 the complexity of libraries like FormEncode.
759
760