toargs(context, schema, data)
Marshal data to an argument dictionary using a schema
Names that are python keywords have an underscore added as a suffix in the schema and in the argument list, but are used without the underscore in the data.
The fields in the schema must all implement IFromUnicode.
All of the items in the data must have corresponding fields in the schema unless the schema has a true tagged value named 'keyword_arguments'.
Here's an example:
>>> from zope import schema
>>> class schema(Interface): ... in_ = zope.schema.Int(constraint=lambda v: v > 0) ... f = zope.schema.Float() ... n = zope.schema.TextLine(min_length=1, default=u"rob") ... x = zope.schema.BytesLine(required=False) ... u = zope.schema.URI()
>>> context = ConfigurationMachine() >>> from pprint import PrettyPrinter >>> pprint=PrettyPrinter(width=50).pprint
>>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org' })) {'f': 1.2, 'in_': 1, 'n': u'bob', 'u': 'http://www.zope.org', 'x': 'x.y.z'}
If we have extra data, we'll get an error:
>>> toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org', 'a': u'1'}) Traceback (most recent call last): ... ConfigurationError: ('Unrecognized parameters:', 'a')
Unless we set a tagged value to say that extra arguments are ok:
>>> schema.setTaggedValue('keyword_arguments', True)
>>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org', 'a': u'1'})) {'a': u'1', 'f': 1.2, 'in_': 1, 'n': u'bob', 'u': 'http://www.zope.org', 'x': 'x.y.z'}
If we ommit required data we get an error telling us what was omitted:
>>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z'})) Traceback (most recent call last): ... ConfigurationError: ('Missing parameter:', 'u')
Although we can omit not-required data:
>>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', ... 'u': u'http://www.zope.org', 'a': u'1'})) {'a': u'1', 'f': 1.2, 'in_': 1, 'n': u'bob', 'u': 'http://www.zope.org'}
And we can ommit required fields if they have valid defaults (defaults that are valid values):
>>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', ... 'u': u'http://www.zope.org', 'a': u'1'})) {'a': u'1', 'f': 1.2, 'in_': 1, 'n': u'rob', 'u': 'http://www.zope.org'}
We also get an error if any data was invalid:
>>> pprint(toargs(context, schema, ... {'in': u'0', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org', 'a': u'1'})) Traceback (most recent call last): ... ConfigurationError: ('Invalid value for', 'in', '0')