Last active
July 2, 2017 03:56
-
-
Save CooperLuan/6bf3af42d1f42096d933 to your computer and use it in GitHub Desktop.
python schema example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| pip install schema | |
| check if people can retire(age 65 for male, 60 for female) | |
| """ | |
| from schema import Schema, And, Use, Optional | |
| schema = Schema([{ | |
| 'name': And(str, len), | |
| 'age': And(Use(int), lambda n: 18 <= n <= 65), | |
| 'sex': And(str, Use(str.lower), | |
| lambda s: s in ('male')), | |
| Optional('single'): bool, | |
| }, { | |
| 'name': And(str, len), | |
| 'age': And(Use(int), lambda n: 18 <= n <= 60), | |
| 'sex': And(str, Use(str.lower), | |
| lambda s: s in ('female')), | |
| Optional('single'): bool, | |
| }]) | |
| data = [ | |
| {'name': 'Sue', 'age': '70', 'sex': 'FEMALE', 'single': True}, | |
| {'name': 'Sue', 'age': '50', 'sex': 'FEMALE', 'single': 1}, | |
| {'name': 'Sacha', 'age': '20', 'sex': 'Male'}, | |
| ] | |
| validated = schema.validate(data) | |
| print(validated) | |
| ''' | |
| File "schema.py", line 53, in validate | |
| [self._error] + x.errors) | |
| schema.SchemaError: Or({'age': And(Use(<type 'int'>), <function <lambda> at 0x7f431551f230>), Optional('single'): <type 'bool'>, 'name': And(<type 'str'>, <built-in function len>), 'sex': And(<type 'str'>, Use(<method 'lower' of 'str' objects>), <function <lambda> at 0x7f431551f410>)}, {Optional('single'): <type 'bool'>, 'age': And(Use(<type 'int'>), <function <lambda> at 0x7f431551f488>), 'name': And(<type 'str'>, <built-in function len>), 'sex': And(<type 'str'>, Use(<method 'lower' of 'str' objects>), <function <lambda> at 0x7f431551f500>)}) did not validate {'age': '70', 'name': 'Sue', 'single': True, 'sex': 'FEMALE'} | |
| <lambda>(70) should evaluate to True | |
| ''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment