From 3550e7a3feac8726e4747457e14932e6010b397b Mon Sep 17 00:00:00 2001 From: mike Date: Sat, 05 Dec 2009 19:22:28 +0000 Subject: BoyScout2.0 : Adding type objects support inside the TypeConstraint --- (limited to 'tutorius/constraints.py') diff --git a/tutorius/constraints.py b/tutorius/constraints.py index 9ac1ca4..ffb646d 100644 --- a/tutorius/constraints.py +++ b/tutorius/constraints.py @@ -57,13 +57,20 @@ class TypeConstraint(Constraint): def __init__(self, expected_type): """ Creates a new type constraint to restrict accepted values to a certain type. - @param expected_type A string describing the name of the type to enforce + @param expected_type A string describing the name of the type to + enforce, or a full-blown type object. If a type + object is used, all objects that inherit from this + type will pass. """ self._expected_type = expected_type def validate(self, value): - if self._expected_type == type(value).__name__: - return value + if type(self._expected_type) == str: + if self._expected_type == type(value).__name__: + return value + else: + if isinstance(value, self._expected_type): + return value raise TypeConstraintError("Wrong type for value %s, got type %s; expected %s" % \ (str(value), type(value).__name__, @@ -116,13 +123,21 @@ class MultiTypeConstraint(Constraint): """ Creates a new type constraint to restrict accepted values to a certain type. @param expected_types_list A list of strings describing the possible names - of the types to enforce. + of the types to enforce, or a list of type + objects. If there are type objects, then + value inheriting from this type will be + validated. """ self._expected_types_list = expected_types_list - + def validate(self, value): - if type(value).__name__ in self._expected_types_list: - return value + for expected_type in self._expected_types_list: + if type(expected_type).__name__ == 'str': + if expected_type == type(value).__name__: + return value + else: + if isinstance(value, expected_type): + return value raise TypeConstraintError("Wrong type for value %s, got type %s; expected one in %s" % \ (str(value), type(value).__name__, -- cgit v0.9.1