Convertors¶
Convertors classes for converting the string input to the desired output type. The GetInput class calls the Convertor after cleaning and before validation.
Creating Convertors¶
Convertor classes inherit from the Convertor base class. They must be callable, with the __call__ dunder method taking three parameters: the value to convert, a function to call when an error occurs and the format string for the error function. The __call__ method returns the converted value. Error conditions are handled by calling the error_callback function . See error_callbacks for more information on error functions and their format strings. The __init__ method should use super to call the __init__ method on the Convertor base class so value_error_str gets set.
An example of a convertor to change the input value to an integer looks like:
class IntConvertor(Convertor):
# convert to a value to an integer
def __init__(self, base=10, value_error_str='an integer number'):
self._base = base
super(IntConvertor, self).__init__(value_error_str)
def __call__(self, value, error_callback, convertor_fmt_str):
try:
return int(value, self._base)
except ValueError:
error_callback(convertor_fmt_str, value, 'an int')
raise # re-raise the exception
def __repr__(self):
return 'IntConvertor(base={}, value_error_str={})'.format(self._base, self.value_error_str)
Convertors¶
BooleanConvertor¶
- class cooked_input.BooleanConvertor(value_error_str='true or false')¶
convert to a boolean value (True or False.)
- Parameters:
value_error_str (
str) – (optional) the error string to use when an improper value is input- Returns:
valueconverted to a boolean- Raises:
ConvertorError – if
valuecannot be converted to bool
BooleanConvertor returns True for input values: ‘t’, ‘true’, ‘y’, ‘yes’, and ‘1’. BooleanConvertor returns False for input values: ‘f’, ‘false’, ‘n’, ‘no’, ‘0’.
DateConvertor¶
- class cooked_input.DateConvertor(value_error_str='a date')¶
convert to a datetime value.
- Parameters:
value_error_str (
str) – (optional) the error string to use when an improper value is input- Returns:
valueconverted to a datetime- Raises:
if dateparser is unable to convert
valueto a datetime
Converts the cleaned input to an datetime value. Dateparser is used for the parsing, allowing a lot of flexibility in how date input is entered (e.g. ‘12/12/12’, ‘October 1, 2015’, ‘today’, or ‘next Tuesday’). For more information about dateparser see: https://dateparser.readthedocs.io/en/latest/
FloatConvertor¶
- class cooked_input.FloatConvertor(value_error_str='a float number')¶
convert to a floating point number.
- Parameters:
value_error_str (
str) – (optional) the error string to use when an improper value is input- Returns:
valueconverted to float- Raises:
ConvertorError – if
valuecannot be converted to float
IntConvertor¶
- class cooked_input.IntConvertor(base=10, value_error_str='an integer number')¶
convert the cleaned input to an integer.
- Parameters:
base (
int) – the radix base to use for the int conversion (default=10)value_error_str (
str) – (optional) the error string to use when an improper value is input
- Returns:
valueconverted to int- Raises:
ConvertorError – if
valuecannot be converted to int
Legal values for the base parameter are 0 and 2-36. See the Python int built-in function for more information.
ListConvertor¶
- class cooked_input.ListConvertor(elem_get_input=None, delimiter=',', value_error_str='list of values')¶
convert to a list.
- Parameters:
elem_get_input (
GetInput|None) – an instance of aGetInputto apply to each element. IfNone(default) each element in the list is a stringdelimiter (
str|None) – (optional) the single character delimiter to use for parsing the list. If None, will sniff the value (ala CSV library.)value_error_str (
str) – (optional) the error string for improper value inputs
- Returns:
a list values, where each item in the list is of the type returned by
elem_get_input- Raises:
ConvertorError – if
elem_get_input’sGetInput.process_value()fails
Converts to a homogenous list of values. The
GetInput.process_value()method on theelem_get_inputGetInputinstance is called for each element in the list.For example, the accept a list of integers separated by colons (‘:’) and return it as a Python list of ints:
prompt_str = 'Enter a list of integers (separated by ":")' lc = ListConvertor(delimiter=':', elem_get_input=GetInput(convertor=IntConvertor())) result = get_input(prompt=prompt_str, convertor=lc)
YesNoConvertor¶
- class cooked_input.YesNoConvertor(value_error_str='yes or no')¶
convert to ‘yes’ or ‘no’.
- Parameters:
value_error_str (
str) – (optional) the error string to use when an improper value is input- Returns:
a string set to either “yes” or “no”
- Raises:
ConvertorError – if
valuecannot be converted to “yes” or “no”
YesNoConvertor returns yes for input values: ‘y’, ‘yes’, ‘yeah’, ‘yup’, ‘aye’, ‘qui’, ‘si’, ‘ja’, ‘ken’, ‘hai’, ‘gee’, ‘da’, ‘tak’, ‘affirmative’. YesNoConvertor returns no for input values: ‘n’, ‘no’, ‘nope’, ‘na’, ‘nae’, ‘non’, ‘negatory’, ‘nein’, ‘nie’, ‘nyet’, ‘lo’.
ChoiceConvertor¶
- class cooked_input.ChoiceConvertor(value_dict, value_error_str='a valid row number')¶
Convert a value to its mapped value in a dictionary.
- Parameters:
value_dict (
dict[Any,Any]) – a dictionary containing keys to map from and values to map tovalue_error_str (
str) – (optional) the error string to use when an improper value is input
:raises ConvertorError if
valuekey is not found invalue_dict- Returns:
the value associated with the choice in
value_dict(e.g. value_dict[value])
convert a value to it’s return value in a dictionary (i.e. value_dict[value]). Can be used to map the row index from a table of values or to map multiple tags to a single choice.
For example, to use a number to pick from a list of colors:
value_map = {'1': 'red', '2': 'green', '3': 'blue'} choice_convertor = ci.ChoiceConvertor(value_dict=value_map) result = ci.get_input(convertor=choice_convertor, prompt='Pick a color (1 - red, 2 - green, 3 - blue)')
DecimalConvertor¶
- class cooked_input.DecimalConvertor(precision=None, rounding='ROUND_HALF_UP', value_error_str='a decimal number')¶
convert the cleaned input to a Decimal value.
- Parameters:
precision (
int|None) – the fixed number of digits after the decimal point. None (the default) keeps every digit entered and rounds nothing.rounding (
str) – rules used for rounding (default: “ROUND_HALF_UP”)value_error_str (
str) – (optional) the error string to use when an improper value is input
- Returns:
valueconverted to Decimal- Raises:
ConvertorError – if
valuecannot be converted to DecimalValueError – at construction, if
roundingis not one of the legal names orprecisionis not a whole number
Converts the value to a Decimal value (see the Python standard library Decimal module for me details.)
precisioncounts digits after the decimal point, not significant digits, soDecimalConvertor(precision=2)('1234.567')givesDecimal('1234.57'). This is what makesget_money()useful:get_money(precision=2)returns an amount in whole cents. A negativeprecisionrounds to the left of the decimal point –precision=-2rounds to hundreds.The rounding parameter sets the rules for rounding the value, and only has an effect when
precisionis set. The default rounding rule is “ROUND_HALF_UP”. Legal values for the rounding parameter are: “ROUND_CEILING”, “ROUND_DOWN”, “ROUND_FLOOR”, “ROUND_HALF_DOWN”, “ROUND_HALF_EVEN”, “ROUND_HALF_UP”, “ROUND_UP”, and “ROUND_05UP”.See the Python Decimal