1. Ludia
  2. Untitled project
  3. onctuous


Jean-Tiare Le Bigot  committed 4b3d9a7

[untested] Coerce is now idenpotent

  • Participants
  • Parent commits 9c892c0
  • Branches default

Comments (0)

Files changed (1)

File onctuous/validators.py

View file
  • Ignore whitespace
     return f
-def Coerce(type, msg=None):
-    """Coerce a value to a type.
+def Coerce(target_type, msg=None):
+    """Coerce a value to a type. If the input value of the validator is already
+    of this type, tha value is retured immediately to prevent stupid crash like
+    datetime(datime()). This way, ``Coerce`` can safely be used to make sure the
+    type is OK.
     If the type constructor throws a ValueError, the value will be marked as
+    :param target_type: target type for the coercion operation. May be any type
+    or callable.
     def f(v):
-            return type(v)
+            if type(v) is target_type:
+                return v
+            return target_type(v)
         except ValueError:
-            raise Invalid(msg or ('expected %s' % type.__name__))
+            raise Invalid(msg or ('expected %s' % target_type.__name__))
     return f