# osc_lib.utils package

## Submodules

## osc_lib.utils.columns module

osc_lib.utils.columns.get_column_definitions(attr_map: list[tuple[str, str, str]], long_listing: bool) → tuple[list[str], list[str]]

  Return table headers and column names for a listing table.

  An attribute map (attr_map) is a list of table entry definitions and the format of the map is as follows:

  Parameters:

    - attr_map –

      a list of table entry definitions. Each entry should be a tuple consisting of (API attribute name, header name, listing mode). For example:

          (
              ('id', 'ID', LIST_BOTH),
              ('name', 'Name', LIST_BOTH),
              ('tenant_id', 'Project', LIST_LONG_ONLY),
          )

      The third field of each tuple must be one of LIST_BOTH, LIST_LONG_ONLY (a corresponding column is shown only in a long mode), or LIST_SHORT_ONLY (a corresponding column is shown only in a short mode).

    - long_listing – A boolean value which indicates a long listing or not. In most cases, parsed_args.long is passed to this argument.

  Returns:

    A tuple of a list of table headers and a list of column names.

osc_lib.utils.columns.get_columns(item: dict[str, Any], attr_map: list[tuple[str, str, str]] | None = None) → tuple[tuple[str, ...], tuple[str, ...]]

  Return pair of resource attributes and corresponding display names.

  Parameters:

    - item –

      a dictionary which represents a resource. Keys of the dictionary are expected to be attributes of the resource. Values are not referred to by this method.

          {
              'id': 'myid',
              'name': 'myname',
              'foo': 'bar',
              'tenant_id': 'mytenan',
          }

    - attr_map –

      a list of mapping from attribute to display name. The same format is used as for get_column_definitions attr_map.

          (
              ('id', 'ID', LIST_BOTH),
              ('name', 'Name', LIST_BOTH),
              ('tenant_id', 'Project', LIST_LONG_ONLY),
          )

  Returns:

    A pair of tuple of attributes and tuple of display names.

        (('id', 'name', 'tenant_id', 'foo'),  # attributes
         ('ID', 'Name', 'Project', 'foo')     # display names

    Both tuples of attributes and display names are sorted by display names in the alphabetical order. Attributes not found in a given attr_map are kept as-is.

## osc_lib.utils.tags module

osc_lib.utils.tags.add_tag_filtering_option_to_parser(parser: ~argparse.ArgumentParser, resource_name: str, enhance_help: ~collections.abc.Callable[[str], str] = <function <lambda>>) → None

  Add tag filtering options to a parser.

  Parameters:

    - parser – argparse.Argument parser object.

    - resource_name – Description of the object being filtered.

    - enhance_help – A callable accepting a single parameter, the (translated) help string, and returning a (translated) help string. May be used by a caller wishing to add qualifying text, such as “Applies to version XYZ only”, to the help strings for all options produced by this method.

osc_lib.utils.tags.add_tag_option_to_parser_for_create(parser: ~argparse.ArgumentParser, resource_name: str, enhance_help: ~collections.abc.Callable[[str], str] = <function <lambda>>) → None

  Add tag options to a parser for create commands.

  Parameters:

    - parser – argparse.Argument parser object.

    - resource_name – Description of the object being filtered.

    - enhance_help – A callable accepting a single parameter, the (translated) help string, and returning a (translated) help string. May be used by a caller wishing to add qualifying text, such as “Applies to version XYZ only”, to the help strings for all options produced by this method.

osc_lib.utils.tags.add_tag_option_to_parser_for_set(parser: ~argparse.ArgumentParser, resource_name: str, enhance_help: ~collections.abc.Callable[[str], str] = <function <lambda>>) → None

  Add tag options to a parser for set commands.

  Parameters:

    - parser – argparse.Argument parser object.

    - resource_name – Description of the object being filtered.

    - enhance_help – A callable accepting a single parameter, the (translated) help string, and returning a (translated) help string. May be used by a caller wishing to add qualifying text, such as “Applies to version XYZ only”, to the help strings for all options produced by this method.

osc_lib.utils.tags.add_tag_option_to_parser_for_unset(parser: ~argparse.ArgumentParser, resource_name: str, enhance_help: ~collections.abc.Callable[[str], str] = <function <lambda>>) → None

  Add tag options to a parser for set commands.

  Parameters:

    - parser – argparse.Argument parser object.

    - resource_name – Description of the object being filtered.

    - enhance_help – A callable accepting a single parameter, the (translated) help string, and returning a (translated) help string. May be used by a caller wishing to add qualifying text, such as “Applies to version XYZ only”, to the help strings for all options produced by this method.

osc_lib.utils.tags.get_tag_filtering_args(parsed_args: Namespace, args: dict[str, Any]) → None

  Adds the tag arguments to an args list.

  Intended to be used to append the tags to an argument list that will be used for service client.

  Parameters:

    - parsed_args – Parsed argument object returned by argparse parse_args.

    - args – The argument list to add tags to.

osc_lib.utils.tags.update_tags_for_set(client: Any, obj: Any, parsed_args: Namespace) → None

  Set the tags on an object.

  Parameters:

    - client – The service client to use setting the tags.

    - obj – The object (Resource) to set the tags on.

    - parsed_args – Parsed argument object returned by argparse parse_args.

osc_lib.utils.tags.update_tags_for_unset(client: Any, obj: Any, parsed_args: Namespace) → None

  Unset the tags on an object.

  Parameters:

    - client – The service client to use unsetting the tags.

    - obj – The object (Resource) to unset the tags on.

    - parsed_args – Parsed argument object returned by argparse parse_args.

## Module contents

Common client utilities

osc_lib.utils.backward_compat_col_lister(column_headers: list[str], columns: list[str], column_map: dict[str, str]) → list[str]

  Convert the column headers to keep column backward compatibility.

  Replace the new column name of column headers by old name, so that the column headers can continue to support to show the old column name by –column/-c option with old name, like: volume list -c ‘Display Name’

  Parameters:

    - column_headers – The column headers to be output in list command.

    - columns – The columns to be output.

    - column_map – The key of map is old column name, the value is new column name, like: {‘old_col’: ‘new_col’}

osc_lib.utils.backward_compat_col_showone(show_object: MutableMapping[str, _T], columns: list[str], column_map: dict[str, str]) → MutableMapping[str, _T]

  Convert the output object to keep column backward compatibility.

  Replace the new column name of output object by old name, so that the object can continue to support to show the old column name by –column/-c option with old name, like: volume show -c ‘display_name’

  Parameters:

    - show_object – The object to be output in create/show commands.

    - columns – The columns to be output.

    - column_map – The key of map is old column name, the value is new column name, like: {‘old_col’: ‘new_col’}

osc_lib.utils.build_kwargs_dict(arg_name: str, value: _T) → dict[str, _T]

  Return a dictionary containing arg_name if value is set.

osc_lib.utils.calculate_header_and_attrs(column_headers: Sequence[str], attrs: Sequence[str], parsed_args: Namespace) → tuple[Sequence[str], Sequence[str]]

  Calculate headers and attribute names based on parsed_args.column.

  When –column (-c) option is specified, this function calculates column headers and expected API attribute names according to the OSC header/column definitions.

  This function also adjusts the content of parsed_args.columns if API attribute names are used in parsed_args.columns. This allows users to specify API attribute names in -c option.

  Parameters:

    - column_headers – A tuple/list of column headers to display

    - attrs – a tuple/list of API attribute names. The order of corresponding column header and API attribute name must match.

    - parsed_args – Parsed argument object returned by argparse parse_args

  Returns:

    A tuple of calculated headers and API attribute names.

osc_lib.utils.env(*vars: str, **kwargs: Any) → str | None

  Search for the first defined of possibly many env vars

  Returns the first environment variable defined in vars, or returns the default defined in kwargs.

osc_lib.utils.find_min_match(items: Sequence[_T], sort_attr: str, **kwargs: Any) → Sequence[_T]

  Find all resources meeting the given minimum constraints

  Parameters:

    - items – A List of objects to consider

    - sort_attr – Attribute to sort the resulting list

    - kwargs – A dict of attributes and their minimum values

  Return type:

    A list of resources osrted by sort_attr that meet the minimums

osc_lib.utils.find_resource(manager: Any, name_or_id: str, **kwargs: Any) → Any

  Helper for the _find_* methods.

  Parameters:

    - manager – A client manager class

    - name_or_id – The resource we are trying to find

    - kwargs – To be used in calling .find()

  Return type:

    The found resource

  This method will attempt to find a resource in a variety of ways. Primarily .get() methods will be called with name_or_id as an integer value, and tried again as a string value.

  If both fail, then a .find() is attempted, which is essentially calling a .list() function with a ‘name’ query parameter that is set to name_or_id.

  Lastly, if any kwargs are passed in, they will be treated as additional query parameters. This is particularly handy in the case of finding resources in a domain.

osc_lib.utils.format_dict(data: dict[str, Any], prefix: str | None = None) → str

  Return a formatted string of key value pairs

  Parameters:

    - data – a dict

    - prefix – the current parent keys in a recursive call

  Return type:

    a string formatted to key=’value’

osc_lib.utils.format_dict_of_list(data: dict[str, list[Any]] | None, separator: str = '; ') → str | None

  Return a formatted string of key value pair

  Parameters:

    - data – a dict, key is string, value is a list of string, for example: {‘public’: [‘2001:db8::8’, ‘172.24.4.6’]}

    - separator – the separator to use between key/value pair (default: ‘; ‘)

  Returns:

    a string formatted to {‘key1’=[‘value1’, ‘value2’]} with separated by separator

osc_lib.utils.format_list(data: list[Any] | None, separator: str = ', ') → str | None

  Return a formatted strings

  Parameters:

    - data – a list of strings

    - separator – the separator to use between strings (default: ‘, ‘)

  Return type:

    a string formatted based on separator

osc_lib.utils.format_list_of_dicts(data: list[dict[str, Any]] | None) → str | None

  Return a formatted string of key value pairs for each dict

  Parameters:

    data – a list of dicts

  Return type:

    a string formatted to key=’value’ with dicts separated by new line

osc_lib.utils.format_size(size: int | float | None) → str

  Display size of a resource in a human readable format

  Parameters:

    size – The size of the resource in bytes.

  Returns:

    Returns the size in human-friendly format

  Rtype string:

  This function converts the size (provided in bytes) of a resource into a human-friendly format such as K, M, G, T, P, E, Z

osc_lib.utils.get_client_class(api_name: str, version: str | int | float, version_map: dict[str, str]) → Any

  Returns the client class for the requested API version

  Parameters:

    - api_name – the name of the API, e.g. ‘compute’, ‘image’, etc

    - version – the requested API version

    - version_map – a dict of client class strings keyed by version

  Return type:

    a client class for the requested API version

osc_lib.utils.get_dict_properties(item: dict[str, _T], fields: Sequence[str], mixed_case_fields: Sequence[str] | None = None, formatters: Mapping[str, type[FormattableColumn[Any]] | partial[Any]] | None = None) → tuple[Any, ...]

  Return a tuple containing the item properties.

  Parameters:

    - item – a single dict resource

    - fields – tuple of strings with the desired field names

    - mixed_case_fields – tuple of field names to preserve case

    - formatters – dictionary mapping field names to callables to format the values

osc_lib.utils.get_effective_log_level() → int

  Returns the lowest logging level considered by logging handlers

  Retrieve and return the smallest log level set among the root logger’s handlers (in case of multiple handlers).

osc_lib.utils.get_field(item: _T, field: str) → Any

osc_lib.utils.get_item_properties(item: dict[str, _T], fields: Sequence[str], mixed_case_fields: Sequence[str] | None = None, formatters: Mapping[str, type[FormattableColumn[Any]] | partial[Any]] | None = None) → tuple[Any, ...]

  Return a tuple containing the item properties.

  Parameters:

    - item – a single item resource (e.g. Server, Project, etc)

    - fields – tuple of strings with the desired field names

    - mixed_case_fields – tuple of field names to preserve case

    - formatters – dictionary mapping field names to callables to format the values

osc_lib.utils.get_osc_show_columns_for_sdk_resource(sdk_resource: Resource, osc_column_map: dict[str, str], invisible_columns: Sequence[str] | None = None) → tuple[tuple[str, ...], tuple[str, ...]]

  Get and filter the display and attribute columns for an SDK resource.

  Common utility function for preparing the output of an OSC show command. Some of the columns may need to get renamed, others made invisible.

  Parameters:

    - sdk_resource – An SDK resource

    - osc_column_map – A hash of mappings for display column names

    - invisible_columns – A list of invisible column names

  Returns:

    Two tuples containing the names of the display and attribute columns

osc_lib.utils.get_password(stdin: TextIO, prompt: str | None = None, confirm: bool = True) → str

osc_lib.utils.is_ascii(string: str | bytes) → bool

osc_lib.utils.is_uuid_like(value: Any) → bool

  Returns validation of a value as a UUID.

  Parameters:

    val – Value to verify

  Returns:

    True if UUID-like, else False.

osc_lib.utils.read_blob_file_contents(blob_file: str) → str

osc_lib.utils.sort_items(items: Sequence[_T], sort_str: str, sort_type: type[Any] | None = None) → Sequence[_T]

  Sort items based on sort keys and sort directions given by sort_str.

  Parameters:

    - items – a list or generator object of items

    - sort_str – a string defining the sort rules, the format is ‘<key1>:[direction1],<key2>:[direction2]…’, direction can be ‘asc’ for ascending or ‘desc’ for descending, if direction is not given, it’s ascending by default

  Returns:

    sorted items

osc_lib.utils.wait_for_delete(manager: Any, res_id: str, status_field: str = 'status', error_status: Sequence[str] = ['error'], exception_name: Sequence[str] = ['NotFound'], sleep_time: int = 5, timeout: int = 300, callback: Callable[[int], None] | None = None) → bool

  Wait for resource deletion

  Parameters:

    - manager – the manager from which we can get the resource

    - res_id – the resource id to watch

    - status_field – the status attribute in the returned resource object, this is used to check for error states while the resource is being deleted

    - error_status – a list of status strings for error

    - exception_name – a list of exception strings for deleted case

    - sleep_time – wait this long between checks (seconds)

    - timeout – check until this long (seconds)

    - callback – called per sleep cycle, useful to display progress; this function is passed a progress value during each iteration of the wait loop

  Return type:

    True on success, False if the resource has gone to error state or the timeout has been reached

osc_lib.utils.wait_for_status(status_f: Callable[[str], object], res_id: str, status_field: str = 'status', success_status: Sequence[str] = ['active'], error_status: Sequence[str] = ['error'], sleep_time: int = 5, callback: Callable[[int], None] | None = None) → bool

  Wait for status change on a resource during a long-running operation

  Parameters:

    - status_f – a status function that takes a single id argument

    - res_id – the resource id to watch

    - status_field – the status attribute in the returned resource object

    - success_status – a list of status strings for successful completion

    - error_status – a list of status strings for error

    - sleep_time – wait this long (seconds)

    - callback – called per sleep cycle, useful to display progress

  Return type:

    True on success

this page last updated: 2026-03-26 21:54:26

Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.

found an error? report a bug