Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/selik/destructure
Easy declarative schema validation with optional name-binding. Gives Python a switch/case.
https://github.com/selik/destructure
Last synced: 2 months ago
JSON representation
Easy declarative schema validation with optional name-binding. Gives Python a switch/case.
- Host: GitHub
- URL: https://github.com/selik/destructure
- Owner: selik
- License: mit
- Created: 2016-05-28T01:39:55.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2016-08-24T13:53:22.000Z (over 8 years ago)
- Last Synced: 2024-08-03T23:15:26.744Z (5 months ago)
- Language: Python
- Homepage:
- Size: 23.4 KB
- Stars: 9
- Watchers: 2
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.rst
- License: LICENSE
Awesome Lists containing this project
- awesome-python-models - destructure - Easy declarative schema validation with optional name-binding. (Data validation)
README
#################
destructure
#################Easy declarative schema validation with optional name-binding.
.. code:: python
>>> from destructure import Binding, match
>>>
>>> o = Binding()
>>> schema = {
... 'string': str,
... 'any': ...,
... 'binding': o.name,
... 'sequence': [1, 2, ...],
... 'mapping': {'a': int, ...: ...},
... }
>>> data = {
... 'string': 'a',
... 'any': 5j,
... 'binding': 42,
... 'sequence': [1, 2, 3, 4],
... 'mapping': {'a': 1, 'b': 2, 'c': 3},
... }
>>> guard = lambda : o.name > 10
>>> data == match(schema, data, guard)
True
>>> o.name
42Pick between several schemas with a handy ``Switch.case``.
.. code:: python
>>> from destructure import Binding, Switch
>>>
>>> o = Binding()
>>> schema1 = [1, o.x, 3]
>>> schema2 = [2, 4, o.x]
>>>
>>> s = Switch([2, 4, 6])
>>> if s.case(schema1):
... print(o.x)
... elif s.case(schema2):
... print(o.x)
... else:
... print('otherwise')
6Schemas may include many kinds of objects, though to make use of
Ellipses or Binding, the class must support keyword arguments and
cannot be too strict with parameter type-checking... code:: python
>>> class Foo:
... def __init__(self, bar):
... self.bar = bar
>>> bind = Binding()
>>> schema = Foo(bar=bind.x)
>>> result = match(schema, Foo(bar=1))
>>> bind.x
1See some `example scripts`_ for a practical usage, in context.
.. _`example scripts`: http://github.com/selik/destructure/tree/master/examples