Add docstrings for utils.helpers

Cleaning up a little technical debt by adding docstrings
for our public APIs.

Note: I plan to submit a patch per file as part of this bug work.
These patches won't depend on each other. The last patch of
the series will close the bug.

Change-Id: I11c23e3be430daa3e618904db4b4016105c7fc04
Partial-Bug: #1614594
This commit is contained in:
Boden R 2016-08-22 16:43:50 -06:00
parent 72c7cd2d31
commit ee03dc1a1a

View File

@ -23,11 +23,12 @@ from neutron_lib._i18n import _
def parse_mappings(mapping_list, unique_values=True, unique_keys=True):
"""Parse a list of mapping strings into a dictionary.
:param mapping_list: a list of strings of the form '<key>:<value>'
:param unique_values: values must be unique if True
:param unique_keys: keys must be unique if True, else implies that keys
and values are not unique
:returns: a dict mapping keys to values or to list of values
:param mapping_list: A list of strings of the form '<key>:<value>'.
:param unique_values: Values must be unique if True.
:param unique_keys: Keys must be unique if True, else implies that keys
and values are not unique.
:returns: A dict mapping keys to values or to list of values.
:raises ValueError: Upon malformed data or duplicate keys.
"""
mappings = {}
for mapping in mapping_list:
@ -63,24 +64,45 @@ def parse_mappings(mapping_list, unique_values=True, unique_keys=True):
def compare_elements(a, b):
"""Compare elements if a and b have same elements.
This method doesn't consider ordering
This method doesn't consider ordering.
:param a: The first item to compare.
:param b: The second item to compare.
:returns: True if a and b have the same elements, False otherwise.
"""
return set(a or []) == set(b or [])
def safe_sort_key(value):
"""Return value hash or build one for dictionaries."""
"""Return value hash or build one for dictionaries.
:param value: The value to build a hash for.
:returns: The value sorted.
"""
if isinstance(value, collections.Mapping):
return sorted(value.items())
return value
def dict2str(dic):
"""Build a str representation of a dict.
:param dic: The dict to build a str representation for.
:returns: The dict in str representation that is a k=v command list for
each item in dic.
"""
return ','.join("%s=%s" % (key, val)
for key, val in sorted(six.iteritems(dic)))
def str2dict(string):
"""Parse a str representation of a dict into its dict form.
This is the inverse of dict2str()
:param string: The string to parse.
:returns: A dict constructed from the str representation in string.
"""
res_dict = {}
for keyvalue in string.split(','):
(key, value) = keyvalue.split('=', 1)
@ -89,12 +111,24 @@ def str2dict(string):
def dict2tuple(d):
"""Build a tuple from a dict.
:param d: The dict to coherence into a tuple.
:returns: The dict d in tuple form.
"""
items = list(d.items())
items.sort()
return tuple(items)
def diff_list_of_dict(old_list, new_list):
"""Given 2 lists of dicts, return a tuple containing the diff.
:param old_list: The old list of dicts to diff.
:param new_list: The new list of dicts to diff.
:returns: A tuple where the first item is a list of the added dicts in
the diff and the second item is the removed dicts.
"""
new_set = set([dict2str(l) for l in new_list])
old_set = set([dict2str(l) for l in old_list])
added = new_set - old_set
@ -103,15 +137,30 @@ def diff_list_of_dict(old_list, new_list):
def get_random_string(length):
"""Get a random hex string of the specified length."""
"""Get a random hex string of the specified length.
:param length: The length for the hex string.
:returns: A random hex string of the said length.
"""
return "{0:0{1}x}".format(random.getrandbits(length * 4), length)
def camelize(s):
"""Camelize a str that uses _ as a camelize token.
:param s: The str to camelize that contains a _ at each index where a new
camelized word starts.
:returns: The camelized str.
"""
return ''.join(s.replace('_', ' ').title().split())
def round_val(val):
"""Round the value.
:param val: The value to round.
:returns: The value rounded using the half round up scheme.
"""
# we rely on decimal module since it behaves consistently across Python
# versions (2.x vs. 3.x)
return int(decimal.Decimal(val).quantize(decimal.Decimal('1'),
@ -119,6 +168,11 @@ def round_val(val):
def safe_decode_utf8(s):
"""Safe decode a str from UTF.
:param s: The str to decode.
:returns: The decoded str.
"""
if six.PY3 and isinstance(s, bytes):
return s.decode('utf-8', 'surrogateescape')
return s