Package konval :: Module typeval :: Class ToType
[hide private]
[frames] | no frames]

Class ToType

source code

                 object --+    
                          |    
basevalidator.BaseValidator --+
                              |
                             ToType
Known Subclasses:

Convert a value to a given type.

This is largely syntactic sugar: It will actually accept any callable as an argument, but is intended for use with class constructors. You could use raw types and classes, but this throws much nicer error messages. Conversion is done by simply passing a value to the parameter callable.

Instance Methods [hide private]
 
__init__(self, to_type, type_name=None)
Class c'tor, accepting a type.
source code
 
make_conversion_error_msg(self, bad_val, err)
Generate an appropriate error message for type conversion problem.
source code
 
convert_value(self, value)
Transform a value to the desired form.
source code

Inherited from basevalidator.BaseValidator: __call__, convert, make_validation_error_msg, raise_conversion_error, raise_validation_error, validate, validate_value

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, to_type, type_name=None)
(Constructor)

source code 

Class c'tor, accepting a type.

For example:

>>> v = ToType(int, type_name='an integer')
>>> v(1)
1
>>> v(2.3)
2
>>> v('foo')
Traceback (most recent call last):
...
ValueError: can't convert 'foo' to an integer
>>> v = ToType(float)
>>> v('foo')
Traceback (most recent call last):
...
ValueError: can't convert 'foo' to float
Parameters:
  • to_type (callable) - A class constructor (old or new style), built-in type, or function that can be called to convert a type and will throw if it fails.
  • type_name (string) - A name for the type produced. If not supplied, it will be extracted from to_type if possible.
Overrides: object.__init__

make_conversion_error_msg(self, bad_val, err)

source code 
Generate an appropriate error message for type conversion problem.
Overrides: basevalidator.BaseValidator.make_conversion_error_msg

convert_value(self, value)

source code 

Transform a value to the desired form.

This is the workhorse method that is called by convert to transform passed values. As such, errors are signalled by throwing a meaningful exception. This is one of the obvious and easiest places to customize behaviour by overriding in a subclass.

Parameters:
  • value - value to be transformed
Returns:
the transformed value
Overrides: basevalidator.BaseValidator.convert_value
(inherited documentation)