How to create a "type-agnostic" SchemaNode in colander
pyramid, python
Solution
Those Colander types derive from SchemaType and implement the methods that actually do the serialisation and deserialisation.
The only way I can think of to do this is write your own implementation of SchemaType that is essentially a wrapper that tests the value and applies one of the types defined in Colander.
I don't think it would be that hard, just not pretty.
Edit: Here's a scratch example. I haven't tested it, but it conveys the idea.
class AnyType(SchemaType):
def serialize(self, node, appstruct):
if appstruct is null:
return null
impl = colander.Mapping() # Or whatever default.
t = type(appstruct)
if t == str:
impl = colander.String()
elif t == int:
impl = colander.Int()
# Test the others, throw if indeterminate etc.
return impl.serialize(node, appstruct)
def deserialize(self, node, cstruct):
if cstruct is null:
return null
# Test and return again.
Problem
I'm trying to use colander to define a SchemaNode that could have any type. I'd like it to just take whatever was deserialized from the JSON and pass it along. Is that possible? ``` class Foo(colander.MappingSchema): name = colander.SchemaNode(colander.String(), validator=colander.Length(max=80)) value = colander.SchemaNode(??) # should accept int, float, string... ```