From 5624d5a72a79a12e4577f18025dad5dafb4b70ca Mon Sep 17 00:00:00 2001 From: Jack Kuan Date: Thu, 11 Aug 2011 17:39:59 +0800 Subject: Made dict and list work as type validators... 1. Made dict and list work as type validators so:: >>> Schema(dict)({'a': 1}) {'a': 1} >>> Schema(list)([1,2,3]) [1, 2, 3] 2. Validation now returns the correct type of instance for subclass of list or dict:: >>> class Dict(dict): ... pass >>> isinstance(Schema(Dict)(Dict(a=1)), Dict) True --- voluptuous.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'voluptuous.py') diff --git a/voluptuous.py b/voluptuous.py index be450a8..31e8abf 100644 --- a/voluptuous.py +++ b/voluptuous.py @@ -160,15 +160,15 @@ class Schema(object): return self.validate([], self.schema, data) def validate(self, path, schema, data): + if isinstance(schema, dict): + return self.validate_dict(path, schema, data) + elif isinstance(schema, list): + return self.validate_list(path, schema, data) type_ = type(schema) if type_ is type: type_ = schema - if type_ is dict: - return self.validate_dict(path, schema, data) - elif type_ is list: - return self.validate_list(path, schema, data) - elif type_ in (int, long, str, unicode, float, complex, object, - types.NoneType) or callable(schema): + if type_ in (int, long, str, unicode, float, complex, object, + list, dict, types.NoneType) or callable(schema): return self.validate_scalar(path, schema, data) raise SchemaError('unsupported schema data type %r' % type(schema).__name__) @@ -232,7 +232,7 @@ class Schema(object): if not isinstance(data, dict): raise Invalid('expected a dictionary', path) - out = {} + out = type(schema)() required_keys = set(key for key in schema if (self.required and not isinstance(key, optional)) @@ -309,7 +309,7 @@ class Schema(object): if not schema: return data - out = [] + out = type(schema)() invalid = None index_path = UNDEFINED for i, value in enumerate(data): -- cgit v1.2.1 From e71af67202598126cc54a9baaeb42fd632bfaba8 Mon Sep 17 00:00:00 2001 From: Jack Kuan Date: Thu, 11 Aug 2011 18:46:36 +0800 Subject: Fixed the mistake of using type(schema) instead of type(data). --- voluptuous.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'voluptuous.py') diff --git a/voluptuous.py b/voluptuous.py index 31e8abf..20da1a1 100644 --- a/voluptuous.py +++ b/voluptuous.py @@ -232,7 +232,7 @@ class Schema(object): if not isinstance(data, dict): raise Invalid('expected a dictionary', path) - out = type(schema)() + out = type(data)() required_keys = set(key for key in schema if (self.required and not isinstance(key, optional)) @@ -309,7 +309,7 @@ class Schema(object): if not schema: return data - out = type(schema)() + out = type(data)() invalid = None index_path = UNDEFINED for i, value in enumerate(data): -- cgit v1.2.1