{ "info": { "author": "Nathaniel Ford", "author_email": "nathaniel.ford@eryri.org", "bugtrack_url": null, "classifiers": [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6" ], "description": "# Morphology is a Python data validation library\n\n[![Build Status](https://travis-ci.org/nathanielford/morphology.png)](https://travis-ci.org/nathanielford/morphology)\n[![Coverage Status](https://coveralls.io/repos/github/nathanielford/morphology/badge.svg?branch=master)](https://coveralls.io/github/nathanielford/morphology?branch=master) \n[![Gitter chat](https://badges.gitter.im/nathanielford.png)](https://gitter.im/nathanielford/Lobby)\n\nMorphology is a Python data validation library. It is 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\nTo file a bug, create a [new issue](https://github.com/nathanielford/morphology/issues/new) on GitHub with a short example of how to replicate the issue.\n\n## Documentation\n\nThe documentation is provided [here](http://nathanielford.github.io/morphology/).\n\n## Changelog\n\nSee [CHANGELOG.md](https://github.com/nathanielford/morphology/blob/master/CHANGELOG.md).\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```\n$ curl 'https://api.twitter.com/1.1/users/search.json?q=python&per_page=20&page=1'\n```\n\nTo validate this we might use a schema like:\n\n```pycon\n>>> from morphology import Schema\n>>> schema = Schema({\n... 'q': str,\n... 'per_page': int,\n... 'page': int,\n... })\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>>> from morphology import Required, All, Length, Range\n>>> 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```\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>>> from morphology import MultipleInvalid, Invalid\n>>> try:\n... schema({})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"required key not provided @ data['q']\"\nTrue\n\n```\n\n...must be a string:\n\n```pycon\n>>> try:\n... schema({'q': 123})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"expected str for dictionary value @ data['q']\"\nTrue\n\n```\n\n...and must be at least one character in length:\n\n```pycon\n>>> try:\n... schema({'q': ''})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"length of value must be at least 1 for dictionary value @ data['q']\"\nTrue\n>>> schema({'q': '#topic'}) == {'q': '#topic', 'per_page': 5}\nTrue\n\n```\n\n\"per\\_page\" is a positive integer no greater than 20:\n\n```pycon\n>>> try:\n... schema({'q': '#topic', 'per_page': 900})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"value must be at most 20 for dictionary value @ data['per_page']\"\nTrue\n>>> try:\n... schema({'q': '#topic', 'per_page': -10})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"value must be at least 1 for dictionary value @ data['per_page']\"\nTrue\n\n```\n\n\"page\" is an integer \\>= 0:\n\n```pycon\n>>> try:\n... schema({'q': '#topic', 'per_page': 'one'})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc)\n\"expected int for dictionary value @ data['per_page']\"\n>>> schema({'q': '#topic', 'page': 1}) == {'q': '#topic', 'page': 1, 'per_page': 5}\nTrue\n\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>>> schema = Schema(1)\n>>> schema(1)\n1\n>>> schema = Schema('a string')\n>>> schema('a string')\n'a string'\n\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>>> schema = Schema(int)\n>>> schema(1)\n1\n>>> try:\n... schema('one')\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"expected int\"\nTrue\n\n```\n\n### URL's\n\nURL's in the schema are matched by using `urlparse` library.\n\n```pycon\n>>> from morphology import Url\n>>> schema = Schema(Url())\n>>> schema('http://w3.org')\n'http://w3.org'\n>>> try:\n... schema('one')\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"expected a URL\"\nTrue\n\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>>> schema = Schema([1, 'a', 'string'])\n>>> schema([1])\n[1]\n>>> schema([1, 1, 1])\n[1, 1, 1]\n>>> schema(['a', 1, 'string', 1, 'string'])\n['a', 1, 'string', 1, 'string']\n\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>>> schema = Schema([])\n>>> try:\n... schema([1])\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"not a valid value @ data[1]\"\nTrue\n>>> schema([])\n[]\n>>> schema = Schema(list)\n>>> schema([])\n[]\n>>> schema([1, 2])\n[1, 2]\n\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>>> from datetime import datetime\n>>> def Date(fmt='%Y-%m-%d'):\n... return lambda v: datetime.strptime(v, fmt)\n\n```\n\n```pycon\n>>> schema = Schema(Date())\n>>> schema('2013-03-03')\ndatetime.datetime(2013, 3, 3, 0, 0)\n>>> try:\n... schema('2013-03')\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"not a valid value\"\nTrue\n\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```\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>>> schema = Schema({1: 'one', 2: 'two'})\n>>> schema({1: 'one'})\n{1: 'one'}\n\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>>> schema = Schema({2: 3})\n>>> try:\n... schema({1: 2, 2: 3})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"extra keys not allowed @ data[1]\"\nTrue\n\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>>> from morphology import ALLOW_EXTRA\n>>> schema = Schema({2: 3}, extra=ALLOW_EXTRA)\n>>> schema({1: 2, 2: 3})\n{1: 2, 2: 3}\n\n```\n\nTo remove additional keys use\n`Schema(..., extra=REMOVE_EXTRA)`:\n\n```pycon\n>>> from morphology import REMOVE_EXTRA\n>>> schema = Schema({2: 3}, extra=REMOVE_EXTRA)\n>>> schema({1: 2, 2: 3})\n{2: 3}\n\n```\n\nIt can also be overridden per-dictionary by using the catch-all marker\ntoken `extra` as a key:\n\n```pycon\n>>> from morphology import Extra\n>>> schema = Schema({1: {Extra: object}})\n>>> schema({1: {'foo': 'bar'}})\n{1: {'foo': 'bar'}}\n\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>>> schema = Schema({1: 2, 3: 4})\n>>> schema({3: 4})\n{3: 4}\n\n```\n\nSimilarly to how extra\\_ keys work, this behaviour can be overridden\nper-schema:\n\n```pycon\n>>> schema = Schema({1: 2, 3: 4}, required=True)\n>>> try:\n... schema({3: 4})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"required key not provided @ data[1]\"\nTrue\n\n```\n\nAnd per-key, with the marker token `Required(key)`:\n\n```pycon\n>>> schema = Schema({Required(1): 2, 3: 4})\n>>> try:\n... schema({3: 4})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"required key not provided @ data[1]\"\nTrue\n>>> schema({1: 2})\n{1: 2}\n\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>>> from morphology import Optional\n>>> schema = Schema({1: 2, Optional(3): 4}, required=True)\n>>> try:\n... schema({})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"required key not provided @ data[1]\"\nTrue\n>>> schema({1: 2})\n{1: 2}\n>>> try:\n... schema({1: 2, 4: 5})\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"extra keys not allowed @ data[4]\"\nTrue\n\n```\n\n```pycon\n>>> schema({1: 2, 3: 4})\n{1: 2, 3: 4}\n\n```\n\n### Recursive / nested schema\n\nYou can use `morphology.Self` to define a nested schema:\n\n```pycon\n>>> from morphology import Schema, Self\n>>> recursive = Schema({\"more\": Self, \"value\": int})\n>>> recursive({\"more\": {\"value\": 42}, \"value\": 41}) == {'more': {'value': 42}, 'value': 41}\nTrue\n\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>>> from morphology import Schema\n>>> person = Schema({'name': str})\n>>> person_with_age = person.extend({'age': int})\n>>> sorted(list(person_with_age.schema.keys()))\n['age', 'name']\n\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>>> from morphology import Object\n>>> class Structure(object):\n... def __init__(self, q=None):\n... self.q = q\n... def __repr__(self):\n... return ''.format(self)\n...\n>>> schema = Schema(Object({'q': 'one'}, cls=Structure))\n>>> schema(Structure(q='one'))\n\n\n```\n\n### Allow None values\n\nTo allow value to be None as well, use Any:\n\n```pycon\n>>> from morphology import Any\n\n>>> schema = Schema(Any(None, int))\n>>> schema(None)\n>>> schema(5)\n5\n\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\n```pycon\n>>> def validate_email(email):\n... \"\"\"Validate email.\"\"\"\n... if not \"@\" in email:\n... raise Invalid(\"This email is invalid.\")\n... return email\n>>> schema = Schema({\"email\": validate_email})\n>>> exc = None\n>>> try:\n... schema({\"email\": \"whatever\"})\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc)\n\"This email is invalid. for dictionary value @ data['email']\"\n>>> exc.path\n['email']\n>>> exc.msg\n'This email is invalid.'\n>>> exc.error_message\n'This email is invalid.'\n\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>>> schema = Schema([[2, 3], 6])\n\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>>> try:\n... schema([[6]])\n... raise AssertionError('MultipleInvalid not raised')\n... except MultipleInvalid as e:\n... exc = e\n>>> str(exc) == \"not a valid value @ data[0][0]\"\nTrue\n\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>>> schema([6])\n[6]\n\n```\n\n## Running tests.\n\nMorphology is using nosetests:\n\n $ nosetests\n\n\n## Why use Morphology over another validation library?\n\n**Validators are simple callables**\n: No need to subclass anything, just use a function.\n\n**Errors are simple exceptions.**\n: A validator can just `raise Invalid(msg)` and expect the user to get\nuseful messages.\n\n**Schemas are basic Python data structures.**\n: Should 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.**\n: Nested data structures are treated in the same way as any other\ntype. Need a list of dictionaries? `[{}]`\n\n**Consistency.**\n: Types in the schema are checked as types. Values are compared as\nvalues. Callables are called to validate. Simple.\n\n## Lineage\n\nMorphology is an almost-direct branch of [this library](https://github.com/alecthomas/voluptuous). \n[This issue](https://github.com/alecthomas/voluptuous/issues/287) was opened, addressing the inappropriate \nnature of the name, but was summarily closed by the original author. Sadly, this prevents an otherwise great library \nfrom being utilized in professional, inclusive settings, and the only solution was to fork it to address this specific \nissue. It is important to recognize that Alec Thomas and the other contributers there should receive all the credit for \nthe functionality here. \n\nIn the future I intend to port any significant upgrades over, and will attempt to keep versions in sync such that one is\ninterchangeable with the other with a simple replace-all. For various build mishagus reasons, morphology minor versions\nwill be equivalent to `10x(parent minor version)+c`, where `c` is 0-9 and just has to do with integration fixes.", "description_content_type": "text/markdown", "docs_url": null, "download_url": "https://pypi.python.org/pypi/morphology", "downloads": { "last_day": -1, "last_month": -1, "last_week": -1 }, "home_page": "https://github.com/nathanielford/morphology", "keywords": "", "license": "BSD", "maintainer": "", "maintainer_email": "", "name": "morphology", "package_url": "https://pypi.org/project/morphology/", "platform": "any", "project_url": "https://pypi.org/project/morphology/", "project_urls": { "Download": "https://pypi.python.org/pypi/morphology", "Homepage": "https://github.com/nathanielford/morphology" }, "release_url": "https://pypi.org/project/morphology/0.11.12/", "requires_dist": null, "requires_python": "", "summary": "# Morphology is a Python data validation library", "version": "0.11.12" }, "last_serial": 4001019, "releases": { "0.11.1": [ { "comment_text": "", "digests": { "md5": "6a819d53b5b05449f3015f7ac6a0c1ad", "sha256": "ef57ef0737a785e7870d8c91967bf000c3ea94cfc045aaf1851dd11c0a925d71" }, "downloads": -1, "filename": "morphology-0.11.1.tar.gz", "has_sig": false, "md5_digest": "6a819d53b5b05449f3015f7ac6a0c1ad", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 37769, "upload_time": "2018-06-07T18:00:56", "url": "https://files.pythonhosted.org/packages/9f/ee/26c4efc56cedd5eb5951297ce6ef083c53b9cd3a2c2a628d412760219366/morphology-0.11.1.tar.gz" } ], "0.11.10": [ { "comment_text": "", "digests": { "md5": "ce7617b11c4c238a6b379b97302477a6", "sha256": "c88f3e6c21ff40bd6f4d14877810ba880b33159f0c221df11999c7aee2702338" }, "downloads": -1, "filename": "morphology-0.11.10.tar.gz", "has_sig": false, "md5_digest": "ce7617b11c4c238a6b379b97302477a6", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 37868, "upload_time": "2018-06-07T22:16:07", "url": "https://files.pythonhosted.org/packages/84/52/db7d844e23640b256fc7eed6f201c33ea425a6c77405fc121eecbfb512df/morphology-0.11.10.tar.gz" } ], "0.11.11": [ { "comment_text": "", "digests": { "md5": "ae489124fd407a81e2135c05d3626767", "sha256": "787f40fb0965b28df38ab8d9a431f1bbb034ef02ea49e8fca8e52192451afb2b" }, "downloads": -1, "filename": "morphology-0.11.11.tar.gz", "has_sig": false, "md5_digest": "ae489124fd407a81e2135c05d3626767", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 40283, "upload_time": "2018-06-07T23:34:14", "url": "https://files.pythonhosted.org/packages/7f/c9/d00a447760bf15116c19109795ba35d79a8263fea7392a0250799b2b2065/morphology-0.11.11.tar.gz" } ], "0.11.12": [ { "comment_text": "", "digests": { "md5": "8219715e5a5010d84a97a0ed949b0cd4", "sha256": "d49654d8c971e38fecea63ead06d0040dfb8469cd42790209e04a00afaf23ded" }, "downloads": -1, "filename": "morphology-0.11.12.tar.gz", "has_sig": false, "md5_digest": "8219715e5a5010d84a97a0ed949b0cd4", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 40344, "upload_time": "2018-06-25T16:41:04", "url": "https://files.pythonhosted.org/packages/4d/b8/f1888b21d300abf7d5b287ef71525d77799b2c760e1ab537e92dcfca8810/morphology-0.11.12.tar.gz" } ] }, "urls": [ { "comment_text": "", "digests": { "md5": "8219715e5a5010d84a97a0ed949b0cd4", "sha256": "d49654d8c971e38fecea63ead06d0040dfb8469cd42790209e04a00afaf23ded" }, "downloads": -1, "filename": "morphology-0.11.12.tar.gz", "has_sig": false, "md5_digest": "8219715e5a5010d84a97a0ed949b0cd4", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 40344, "upload_time": "2018-06-25T16:41:04", "url": "https://files.pythonhosted.org/packages/4d/b8/f1888b21d300abf7d5b287ef71525d77799b2c760e1ab537e92dcfca8810/morphology-0.11.12.tar.gz" } ] }