Skip to content

Commit

Permalink
specify optional fields with "missing=drop"
Browse files Browse the repository at this point in the history
  • Loading branch information
abrookins committed Feb 20, 2013
1 parent ff6d8c2 commit 21f5259
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
14 changes: 13 additions & 1 deletion colander/__init__.py
Expand Up @@ -40,6 +40,15 @@ def __reduce__(self):


null = _null() null = _null()


class _drop(object):
"""
Represents a value that should be dropped if it is missing during
deserialization.
"""
pass

drop = _drop()

def interpolate(msgs): def interpolate(msgs):
for s in msgs: for s in msgs:
if hasattr(s, 'interpolate'): if hasattr(s, 'interpolate'):
Expand Down Expand Up @@ -531,11 +540,14 @@ def _impl(self, node, value, callback):
name = subnode.name name = subnode.name
subval = value.pop(name, null) subval = value.pop(name, null)
try: try:
result[name] = callback(subnode, subval) sub_result = callback(subnode, subval)
except Invalid as e: except Invalid as e:
if error is None: if error is None:
error = Invalid(node) error = Invalid(node)
error.add(e, num) error.add(e, num)
else:
if sub_result is not drop:
result[name] = sub_result


if self.unknown == 'raise': if self.unknown == 'raise':
if value: if value:
Expand Down
10 changes: 10 additions & 0 deletions colander/tests/test_colander.py
Expand Up @@ -2895,6 +2895,16 @@ class MySchema(colander.Schema):
self.assertEqual(node.children[2].title, '') self.assertEqual(node.children[2].title, '')
self.assertEqual(node.children[3].title, 'thing2') self.assertEqual(node.children[3].title, 'thing2')


def test_deserialize_drop(self):
import colander
class MySchema(colander.Schema):
a = colander.SchemaNode(colander.String())
b = colander.SchemaNode(colander.String(), missing=colander.drop)
node = MySchema()
expected = {'a': 'test'}
result = node.deserialize(expected)
self.assertEqual(result, expected)

class TestSequenceSchema(unittest.TestCase): class TestSequenceSchema(unittest.TestCase):
def test_succeed(self): def test_succeed(self):
import colander import colander
Expand Down

0 comments on commit 21f5259

Please sign in to comment.