uielements

Back to the docs main page

This module contains the low level text UI elements for the package textui.

This module contains the functions that actually handle user input. Each function is configured so that the user input occurs within a while True loop. Input checking is done on the user input and the loop will not exit if an invalid value was given.

You are welcome to use these functions directly in your programs if you do not wish to use the menu construct classes also provided in the textui package.

Usage

This module contains two groups of functions: standard interactive functions and optional input functions. The former is for cases where you always want to query user input, the second is for cases where you may need to query user input if a particular value is not given programmatically.

Examples

The standard interactive functions are generally pretty straightforward. Here is an example using user_input_date() (lines beginning with $ are the code, the others are printed by Python):

$ user_date = user_input_date('Enter the first date to load data for')
Enter the first date to load data for
Enter in one of the formats: yyyy-mm-dd
Entering nothing will cancel
--> 2017-01-01

$ user_date
datetime.datetime(2017, 1, 1, 0, 0)

As you can see, this asks the user to input a date in a standard format and then returns that as a datetime.datetime object.

One possible “gotcha” is hinted at by the line “Entering nothing will cancel”. For most of the user_input functions, if the user presses <Enter> without entering anything, the function will immediately return a None. Most of them can override this with the emptycancel keyword, which will force the user to enter something. In general, these functions are written with the idea that the encapsulating program will handle the return of None as a signal to gracefully stop, or otherwise handle the fact that the user does not know what to enter.

Here is an example case where you might use one of the optional input functions, in this case opt_user_input_value():

def read_data_from_file(filename=None):
    filename = opt_user_input_value('Enter the name of the file to open',
                                    filename,
                                    is_valid_test=os.path.isfile,
                                    invalid_msg='That is not a valid filename')
    with open(filename, 'r') a fobj:
        ...

You could imagine read_data_from_file being a function called early on in a larger program that loads some data file so that the rest of the program can access it. In this case, we allow the path of the file to be given in two ways:

  1. As an argument to the read_data_from_file function
  2. Interactively, through the opt_user_input_value function

The standard behavior of all the “opt” functions is that if the value (the second argument) is None, then it assumes that the value was not given and so should ask the user to provide it interactively (this criteria can be overridden with the do_ask_test keyword). In this case, we also want to ensure that, whichever way the filename is given, that it is a valid file, so we give is_valid_test=os.path.isfile. This means that either filename (if not None) or the user’s input will be given to os.path.isfile, which must return True for that value to be accepted. This ensures consistent testing of both function inputs and user inputs.

For the “opt” functions that call “user_input” functions that may return None if the user doesn’t enter anything, the “opt” functions will, by default, raise a textui.uierrors.UIOptNoneError. This behavior can be overridden with the error_on_none keyword.

Member functions

Standard interactive functions

textui.uielements.user_input_date(prompt, currentvalue=None, emptycancel=True, req_time_part='day', smallest_allowed_time_part=None)[source]

Request that the user input a date.

Parameters:
  • prompt (str) – A string printed as the prompt; it should describe what date is being requested.
  • currentvalue (datetime.date or datetime.datetime) – optional, if given, will print out the current value given. Useful when setting an option so that the user knows what the current value is.
  • emptycancel (bool) – optional, defaults to True. A boolean determining whether an empty answer will cause this function to return None. If false, the user must enter a valid date to exit (not recommended for most cases).
  • req_time_part (str) – optional, defaults to ‘day’. A string describing the largest required time part, must be one of: ‘year’, ‘month’, ‘day’, ‘hour’, ‘minute’, ‘second’. If this is set to ‘minute’ for example, then the user must input at least year, month, day, hour, and minute, or it will be rejected.
  • smallest_allowed_time_part (str) – optional, defaults to None. A string describing the smallest piece of time the user is allowed to specify. Must be one of the same strings as allowed for req_time_part, and must be the same or smaller piece of time than req_time_part. For example, if this is set to ‘minute’, then the user may not include seconds in their answer. If left as None, then it will be automatically set to the same as req_time_part, effectively giving the user only one choice for how specific to make their time.
Returns:

A datetime.datetime instance, or None.

textui.uielements.user_input_list(prompt, options, returntype='value', currentvalue=None, emptycancel=True, printcols=True, **printcolargs)[source]

This function provides the user a list of choices to choose from, the user selects one by its number

Parameters:
  • prompt (str) – The text prompt to display for the user
  • options (list or tuple) – The list of options to present
  • returntype (str) – optional, can be “value” or “index”, “value” is default. If set to “value”, the return value will be the value of the option chosen. If set to “index”, the return value will be the index of the list chosen.
  • currentvalue – optional, defaults to None. Sets what the current value of this option is. If one is given, it will be marked with a * in the list.
  • emptycancel (bool) – optional, defaults to True. If True, then this function will return None if no answer is chosen (but not if an invalid selection is chosen). A message indicating that an empty answer will cancel is added to the prompt. If False, the list of options will be re-presented if no answer given.
  • printcols (bool) – optional, controls whether the individual options should be spread out across the terminal in columns (True) or all printed in one column (False).
  • printcolargs – keyword arguments to be passed through to textui.uiutils.print_in_columns(). Only has an effect if printcols is True.
Returns:

either the value or index of the user choice (see returntype) or the type None.

textui.uielements.user_input_value(prompt, testfxn=None, testmsg=None, currval=None, returntype=<class 'str'>, emptycancel=True)[source]

Ask the user to input a value.

Parameters:
  • prompt (str) – The prompt to give the user
  • testfxn (function) – optional, if given, should be a function that returns a boolean value. Used to test if the value the user gave is valid. This can be a pre-defined function or one created using the lambda syntax. This will be called after the user input is converted to the returntype given (see below)
  • testmsg (str) – optional, if given, should be a message that describes the conditions required by testfxn. If testfxn is given, this really should be as well, or the user will just see “That is not an allowed value”, which isn’t very helpful.
  • currval – optional, the current value of the option. If given, the value will be printed after the prompt
  • returntype (str) – optional, must be a type which can be used as a function to convert a string to that type, e.g. int, bool, float, list. If the type is bool, this function will require the user to enter T or F (or nothing if emptycancel is True). If not given, the user input will be returned as a string.
  • emptycancel (bool) – optional, defaults to True. If True, then the user can enter an empty string, which will make this function return None.
Returns:

The user input value as the type specified by returntype, or None if emptycancel is True and the user does not enter a value.

textui.uielements.user_input_yn(prompt, default='y')[source]

Prompts the user with a yes/no question, returns True if answer is yes, False if answer is no.

This is similar to user_input_value with a bool return type, but handles it differently if the user does not enter a value; this function will return the default value rather than a None type or forcing the user to enter something

Parameters:
  • prompt (str) – The prompt string that the user should be shown
  • default (bool) – optional, must be either the string “y” or “n”. Sets the default answer.
Returns:

bool

textui.uielements.user_onoff_list(prompt, options, currentstate=None, feedback_level=2, returntype='opts', printcols=True, **printcolargs)[source]

Provides a list of toggleable options to the user

Will print the prompt followed by the list of options provided. The user can interactively toggle each option on or off.

Parameters:
  • prompt (str) – A string prompting the user what to do. Will be followed by further instructions on what user inputs are valid.
  • options (list or tuple) – A list or tuple of strings of the option names
  • currentstate (list of bools) – optional, describe the current state of the options (on or off). If not given, all default to False. Must be the same length as options. Is shallow copied internally so it will not change the values in the calling function.
  • feedback_level (int) – optional, an integer describing how much feedback to give the user. Defaults to 2, meaning that this function will print out what user input it could not parse. Set to 0 to turn this off (1 reserved against future intermediate levels of feedback).
  • returntype (str) – optional, a string determining what is returned. Default is “opts”, which returns a list of the subset of options selected. May also be “bools”, meaning that a list of booleans the same length as options is returned, True for what options the user selected.
  • printcols (bool) – optional, controls whether the individual options should be spread out across the terminal in columns (True) or all printed in one column (False).
  • printcolargs – keyword arguments to be passed through to textui.uiutils.print_in_columns(). Only has an effect if printcols is True.
Returns:

a list of options selected (returntype == “opts”), or a list of bools with the new states of the options (returntype == “bools”), or None if the user cancels.

Optional input functions

textui.uielements.opt_user_input_date(prompt, value, do_ask_test=None, is_valid_test=None, invalid_msg=None, error_on_none=True, **kwargs)[source]

Wrapper around user_input_date that calls it only if an interactive input is necessary.

Parameters:
  • prompt (str) – A string that is the prompt that will be given if the user needs enter a date
  • value – the current value of the date.
  • do_ask_test (function) – optional, a function that should take one input (value) and return True if user_input_date should be called to ask the user what value to use. By default, tests if value is None (i.e. will call user_input_date if value is None).
  • is_valid_test (function) – optional, if given, it must be a function that takes one input (value) and returns a boolean indicating if value is valid. By default, this checks that value is an instance of datetime.date or datetime.datetime.
  • invalid_msg (str) – optional, the error message that will be given in is_valid_test(value) returns False. If is_valid_test is given, this must also be given.
  • error_on_none (bool) – optional, default True, meaning that if the user fails to provide a value, a UIOptNoneError is raised.
  • kwargs – additional keyword arguments to pass through to user_input_date.
Returns:

the date, either given as value or chosen by the user.

textui.uielements.opt_user_input_list(prompt, value, options, do_ask_test=None, invalid_msg=None, error_on_none=True, **kwargs)[source]

Wrapper around user_input_list that calls it only if an interactive choice is necessary.

This function takes mostly the same arguments as user_input_list, but in addition takes an existing value and tests if that value indicates that a choice needs to be made, or if not, that it is a valid option. Typically, this would be used inside a function that has optional arguments that, if not given, should be asked interactively of the user.

Parameters:
  • prompt (str) – A string that is the prompt that will be given if the user needs to make an interactive choice
  • value – the current value that will be tested if it means the user should be asked to choose an option or if it is valid
  • options (list) – a list of allowed options, passed to user_input_list if needed.
  • do_ask_test (function) – optional, a function that should take one input (value) and return True if user_input_list should be called to ask the user what value to use. By default, tests if value is None (i.e. will call user_input_list if value is None).
  • invalid_msg (str) – optional, the message for the UIValueError raised if user_input_list is not called but value is not in the options list. This can have two formatting markers, {value} and {opts}. {value} will be replaced with the value given, {opts} will be replaced with a comma separated list of allowed options.
  • error_on_none (bool) – optional, default True, meaning that if the user fails to provide a value, a UIOptNoneError is raised.
  • kwargs – additional keyword arguments recognized by user_input_list.
Returns:

the value selected, or the value given if user_input_list is not called. Raises a ValueError if value is not in options and user_input_list is not called.

textui.uielements.opt_user_input_value(prompt, value, do_ask_test=None, is_valid_test=None, invalid_msg=None, error_on_none=True, **kwargs)[source]

Wrapper around user_input_value that calls it only if an interactive input is necessary

Parameters:
  • prompt (str) – A string that is the prompt that will be given if the user needs enter a value
  • value – the current value
  • do_ask_test (function) – optional, a function that should take one input (value) and return True if user_input_value should be called to ask the user what value to use. By default, tests if value is None (i.e. will call user_input_value if value is None).
  • is_valid_test (function) – optional, if given, it must be a function that takes one input (value) and returns a boolean indicating if value is valid. If not given, no check of the value will be done. This will also be passed through to user_input_value as testfxn, ensuring that the criteria for the given value is the same in both.
  • invalid_msg (str) – optional, the error message that will be given in is_valid_test(value) returns False. If is_valid_test is given, this must also be given. This will be passed through to user_input_valid as testmsg so that the error message is consistent.
  • kwargs – additional keyword arguments to pass through to user_input_value, except testfxn and testmsg, which are already handled by is_valid_test and invalid_msg, respectively.
  • error_on_none (bool) – optional, default True, meaning that if the user fails to provide a value, a UIOptNoneError is raised.
Returns:

the value, either input as value or entered by the user.

textui.uielements.opt_user_input_yn(prompt, value, do_ask_test=None, **kwargs)[source]

Wrapper around user_input_yn that calls it only if an interactive choice is required.

Parameters:
  • prompt (str) – A string that is the prompt that will be given if the user needs to choose interactively
  • value – the current value. If it does not pass do_ask_test and is not a boolean, an error will be raised
  • do_ask_test (function) – optional, a function that should take one input (value) and return True if user_input_yn should be called to ask the user what value to use. By default, tests if value is None (i.e. will call user_input_yn if value is None).
  • kwargs – additional keyword arguments to pass through to user_input_yn
Returns:

the value, either input as value or chosen by the user.

textui.uielements.opt_user_onoff_list(prompt, value, options, do_ask_test=None, returntype='opts', value_name='The value', **kwargs)[source]

Wrapper around user_onoff_list that calls it only if an interactive choice is required.

Parameters:
  • prompt (str) – A string that is the prompt that will be given if the user needs to choose interactively
  • value – the current value. If this does not pass do_ask_test, then it must be a list or tuple, of what depends on returntype
  • options (list) – the list of options to choose from.
  • do_ask_test (function) – optional, a function that should take one input (value) and return True if user_onoff_list should be called to ask the user what value to use. By default, tests if value is None (i.e. will call user_onoff_list if value is None).
  • returntype (str) – optional, either the string “opts” or “bools”. The default is “opts”, which is the reverse of user_onoff_list; it is assumed that this function is more likely to be used if a list of options is more likely to be passed as an argument than a list of booleans.
  • value_name (str) – optional, but recommended: this will be inserted into the error message raised if value does not pass do_ask_test and is not the right format for the value of returntype as the name of the parameter that is wrong. Otherwise, it just say “The value”, which isn’t very informative for your user.
  • kwargs – additional keyword arguments to pass through to user_onoff_list, except returntype, which is already passed automatically.
Returns:

either a list of booleans the same length as options or a list of the subset of options selected, depending on the value of returntype. Will either be the input value, or the user’s choice.