Convenience Functions¶
Using these convenience functions you can get up and running in cooked_input
very quickly.
Most users can just use these convenience functions and never have to go deeper into the library.
The convenience functions can also take advantage of the rich set up Cleaners,
Convertors, and Validators in the
cooked_input
library.
GetInput Convenience Functions¶
These functions create a GetInput
object with parameter values for the type desired (e.g. the
convertor and a reasonable prompt and cleaners.) The convenience functions are just syntactic sugar for
calls to GetInput
, but simpler to use. For instance, the following two versions calls do the same thing:
# GetInput version:
gi = GetInput(prompt='Enter a whole number', convertor=IntConvertor())
result = gi.get_input()
# Convenience function:
result = get_int(prompt='Enter a whole number')
get_string¶
-
cooked_input.
get_string
(cleaners=StripCleaner(lstrip=True, rstrip=True), validators=None, min_len=None, max_len=None, **options)¶ Parameters: - cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value.
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- min_len (int) – the minimum allowable length for the string. No minimum length if None (default)
- max_len (int) – the maximum allowable length for the string. No maximum length if None (default)
- options – all
GetInput
options supported, seeGetInput
documentation for details.
Returns: the cleaned, converted, validated string
Return type: str
Convenience function to get a string value.
- cleaners (List[Cleaner]) –
get_int¶
-
cooked_input.
get_int
(cleaners=None, validators=None, minimum=None, maximum=None, base=10, **options)¶ Parameters: - cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value.
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- minimum (int) – minimum value allowed. Use None (default) for no minimum value.
- maximum (int) – maximum value allowed. Use None (default) for no maximum value.
- base (int) – Convert a string in radix base to an integer. Base defaults to 10.
- options – all
GetInput
options supported, seeGetInput
documentation for details.
Returns: the cleaned, converted, validated int value
Return type: int
Convenience function to get an integer value. See the documentation for the Python int builtin function for further description of the base parameter.
- cleaners (List[Cleaner]) –
get_float¶
-
cooked_input.
get_float
(cleaners=None, validators=None, minimum=None, maximum=None, **options)¶ Parameters: - cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value.
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- minimum (float) – minimum value allowed. Use None (default) for no minimum value.
- maximum (float) – maximum value allowed. Use None (default) for no maximum value.
- options – all
GetInput
options supported, seeGetInput
documentation for details.
Returns: the cleaned, converted, validated float value
Return type: float
Convenience function to get an float value.
- cleaners (List[Cleaner]) –
get_boolean¶
-
cooked_input.
get_boolean
(cleaners=StripCleaner(lstrip=True, rstrip=True), validators=None, **options)¶ Parameters: - cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value.
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- options – all
GetInput
options supported, seeGetInput
documentation for details.
Returns: the cleaned, converted, validated boolean value
Return type: bool
Convenience function to get a Boolean value. See
BooleanConvertor
for a list of values accepted for True and False.- cleaners (List[Cleaner]) –
get_date¶
-
cooked_input.
get_date
(cleaners=StripCleaner(lstrip=True, rstrip=True), validators=None, minimum=None, maximum=None, **options)¶ Parameters: - cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value. Not needed in general.
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- minimum (datetime) – earliest date allowed. Use None (default) for no minimum value.
- maximum (datetime) – latest date allowed. Use None (default) for no maximum value.
- options – all
GetInput
options supported, seeGetInput
documentation for details.
Returns: the cleaned, converted, validated date value
Return type: Convenience function to get a date value. See
DateConvertor
for more information on converting dates. Get_date can be used to get both times and dates.- cleaners (List[Cleaner]) –
get_yes_no¶
-
cooked_input.
get_yes_no
(cleaners=StripCleaner(lstrip=True, rstrip=True), validators=None, **options)¶ Parameters: - cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value. Not needed in general.
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- options – all
GetInput
options supported, seeGetInput
documentation for details.
Returns: the cleaned, converted, validated yes/no value
Return type: str (“yes” or “no”)
Convenience function to get an yes/no value. See
YesNoConvertor
for a list of values accepted for yes and no.- cleaners (List[Cleaner]) –
get_list¶
-
cooked_input.
get_list
(elem_get_input=None, cleaners=None, validators=None, value_error_str=u'list of values', delimiter=u', ', **options)¶ Parameters: - elem_get_input (GetInput) – an instance of a
GetInput
to apply to each element - cleaners (List[Cleaner]) – cleaners to be applied to the input line before the
ListConvertor
is applied. - validators (List[Validator]) –
list of validators to apply to validate the converted list
- value_error_str (str) – the error string for improper value inputs
- delimiter (str) – the delimiter to use between values
- options – all get_input options supported, see get_input documentation for details.
Returns: the cleaned, converted, validated list of values. For more information on the value_error_str, delimeter, elem_convertor, and elem_valudator` parameters see
ListConvertor
.Return type: List[Any]
Get a homogenous list of values. The
GetInput.process_value()
method on theelem_get_input
GetInput
instance is called for each element in the list.Example usage - get a list of integers between 3 and 5 numbers long, separated by colons (:):
elem_gi = GetInput(convertor=IntConvertor()) length_validator = RangeValidator(min_val=3, max_val=5) list_validator = ListValidator(len_validator=length_validator) prompt_str = 'Enter a list of integers, each between 3 and 5, separated by ":"' result = get_list(prompt=prompt_str, elem_get_input=elem_gi, validators=list_validator, delimiter=":")
- elem_get_input (GetInput) – an instance of a
get_input¶
-
cooked_input.
get_input
(cleaners=None, convertor=None, validators=None, **options)¶ Parameters: - cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value. Not needed in general.
- convertor (Convertor) – the convertor to apply to the cleaned value
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- options – all
GetInput
options supported, seeGetInput
documentation for details.
Returns: the cleaned, converted, validated input string
Return type: Any (returned value is dependent on type returned from
convertor
)Convenience function to create a
GetInput
instance and call its get_input function. SeeGetInput.get_input()
for more details.- cleaners (List[Cleaner]) –
process_value¶
-
cooked_input.
process_value
(value, cleaners=None, convertor=None, validators=None, error_callback=<function print_error>, convertor_error_fmt='"{value}" cannot be converted to {error_content}', validator_error_fmt='"{value}" {error_content}')¶ Parameters: - value (str) – the value to process
- cleaners (List[Cleaner]) –
list of cleaners to apply to clean the value
- convertor (Convertor) –
the convertor to apply to the cleaned value
- validators (List[Validator]) –
list of validators to apply to validate the cleaned and converted value
- error_callback (str) – a callback function to call when an error is encountered. Defaults to
print_error()
- convertor_error_fmt (str) – format string to use for convertor errors. Defaults to DEFAULT_CONVERTOR_ERROR
- validator_error_fmt (str) – format string to use for validator errors. Defaults to DEFAULT_VALIDATOR_ERROR
Returns: the cleaned, converted validated input value.
Return type: Any (returned value is dependent on type returned from
convertor
)Convenience function to create a
GetInput
instance and call its process_value function. SeeGetInput.process_value()
for more details. SeeGetInput
for more information on the error_callback, convertor_error_fmt, and validator_error_fmt parameters.
validate¶
-
cooked_input.
validate
(value, validators, error_callback=<function print_error>, validator_fmt_str='"{value}" {error_content}')¶ return True is a value passes validation.
Parameters: - value (Any) – the value to validate
- validators (List[Validator]) –
an iterable (list or tuple) of validators to run on
value
- error_callback (Callable) – a function called when an error occurs during validation
- validator_fmt_str (str) – format string to pass to the error callback routine for formatting the error
Returns: True if the input passed validation, else False
Return type: boolean
Table Convenience Functions¶
These functions create a Table
object with everything needed to display a simple menu or table. The convenience
functions are just syntactic sugar for calls to Table
, but simpler to use. For instance, the following two
versions do the same thing:
# GetInput version:
menu_choices = [ TableItem('red'), TableItem('green'), TableItem('blue') ]
menu = Table(rows=menu_choices, prompt='Pick a color')
result = menu.get_table_choice()
# Convenience function:
result = get_menu(['red', 'green', 'blue'], prompt='Pick a color')
create_rows¶
-
cooked_input.
create_rows
(items, fields, gen_tags=None, item_data=None, add_item_to_item_data=False)¶ Create a list of TableItems from an iterable (items) of objects
Parameters: - items – iterable containing items for the table.
- fields (List[str]) – list of field/attribute names to use as column values for each item.
- gen_tags (bool) – if True will generate sequentially numbered tags for table items, if False (default) uses first column value of each item for the row’s tag.
- item_data (Dict) – An optional dictionary to be copied and attached to the
TableItem
for the row. - add_item_to_item_data (bool) – if True
item_data['item']
is set to item.
Returns: List[TableItem] of table items (
TableItem
)create_rows
is a convenience function used to create a list of table items (TableItem
) for acooked_input
Table
.create_rows
tries to make it easy to create the rows for a table from a list of data or a query.create_rows
takes an iterable ofitems
, such as a list, dictionary or query. The items initems
can be just about anything too: objects, lists, dictionaries, tuples, or namedtuples.create_rows
also takes a list offields
with each item in the list the name of a field or attribute in the items.create_rows
iterates throughitems
and add the value for each field as a column value for the table row.create_rows
fetches the field data based on the following:1. If ``hasattr`` for the fields returns **True** (**__getattr__** is defined), uses ``getattr`` to retreive field values. This works nicely for class instances, named tuples, and database query results from an object-relationship mapper (ORM). 2. If the items are dictionaries, uses ``get`` to retreive the value for the key matching the field name. 3. If both of the previous methods fail, the first len(fields) values of the item are used (requires **__get_item__** to be defined.)
Note
Care is taken to make a single pass through the
items
iterable as some iterables are non-reentrant (e.g. generators and some database queries)Example usage - get a list of integers between 3 and 5 numbers long, separated by colons (:):
class Person(object): def __init__(self, first, last, age, shoe_size): self.first = first self.last = last self.age = age self.shoe_size = shoe_size people = [ Person('John', 'Cleese', 78, 14), Person('Terry', 'Gilliam', 77, 10), Person('Eric', 'Idle', 75, 12), ] rows = create_rows(people, ['last', 'first', 'shoe_size']) Table(rows, ['First', 'Shoe Size'], tag_str='Last').show_table()
create_rows
is called bycreate_table()
to create the table rows.
create_table¶
-
cooked_input.
create_table
(items, fields, field_names=None, gen_tags=None, item_data=None, add_item_to_item_data=False, title=None, prompt=None, default_choice=None, default_str=None, default_action='table_item', style=None, **options)¶ Convenience function to create
cooked_input
a table.Parameters: - items – iterable containing items for the table.
- fields (List[str]) – list of field/attribute names to use as column values for each item.
- field_names (List[str]) – a list of strings to use for the names of the table columns.
- gen_tags (bool) – if True will generate sequentially numbered tags for table items, if False (default) uses first column value of each item for the row’s tag.
- item_data (Dict) – An optional dictionary to be copied and attached to the
TableItem
for the row. - add_item_to_item_data (bool) – if True
item_data['item']
is set to item. - title (str) – an optional string to use as the title for the table.
- prompt (str) – an optional string to use for the table prompt.
- default_choice (str) – an optional default value to use for when getting input from the table.
- default_str (str) – an optional string to display for the default choice value.
- default_action – the default action to take when a table item is picked. Defaults to TABLE_RETURN_TABLE_ITEM*.
- style (TableStyle) – an optional
TableStyle
to use for the table. - options – a dictionary of optional values for the table. See
Table
for details.
Returns: an instance of a
cooked_input
Table
create_table
is a convenience function used to create acooked_input
table (Table
) from a list of data or a query.create_table
callscreate_rows()
to create the table rows. Seecreate_rows()
for an explanation of the:items
,fields
,gen_tags
,item_data
, andadd_item_to_item_data
parameters.- See
Table
for an explanation of the:title
,prompt
,default_choice
,default_str
, default_action
,style
andoptions
parameters.
Note
all items are created with the same
default_action
anditem_data
(with exception of adding the item toitem_data['item']
ifadd_item_to_item_data
is True.)Note
By default all items (rows) are visible and enabled. Rows can be hidden or disabled by setting an
item_filter
value in theoptions
dictionary.Example usage - get a list of integers between 3 and 5 numbers long, separated by colons (:):
items = { 1: {"episode": 1, "name": "Whither Canada?", "date": "5 October, 1969", "season": 1}, 2: {"episode": 4, "name": "Owl Stretching Time", "date": "26 October, 1969", "season": 1}, 3: {"episode": 15, "name": "The Spanish Inquisition", "date": "22 September, 1970", "season": 2}, 4: {"episode": 35, "name": "The Nude Organist", "date": "14 December, 1972", "season": 2} } fields = 'episode name date'.split() field_names = 'Episode Name Date'.split() tbl = create_table(items, fields, field_names, add_item_to_item_data=True, title='Episode List') choice = tbl.get_table_choice() item = choice.item_data["item"] print('{}: {}'.format(item['name'], item['season']))
show_table¶
get_table_input¶
-
cooked_input.
get_table_input
(table, **options)¶ Get input value from a table of values.
Parameters: Returns: the value from calling
Table.get_table_choice()
on the tableReturn type: Any (dependent on the action function of the
TableItem
selected)