Added docstrings to methods. #2

This commit is contained in:
Fabio Caccamo 2019-12-12 18:24:16 +01:00
parent 723713a8e4
commit fe2dd47d77
4 changed files with 161 additions and 0 deletions

View File

@ -9,65 +9,141 @@ from benedict.utils import dict_util
class benedict(IODict, KeypathDict, ParseDict):
def __init__(self, *args, **kwargs):
"""
Constructs a new instance.
"""
super(benedict, self).__init__(*args, **kwargs)
def clean(self, strings=True, dicts=True, lists=True):
"""
Clean the current dict instance removing all empty values: None, '', {}, [], ().
If strings, dicts or lists flags are False, related empty values will not be deleted.
"""
dict_util.clean(self, strings=strings, dicts=dicts, lists=lists)
def clone(self):
"""
Creates and return a clone of the current dict instance (deep copy).
"""
return dict_util.clone(self)
def copy(self):
"""
Creates and return a copy of the current instance (shallow copy).
"""
return benedict(super(benedict, self).copy())
def deepcopy(self):
"""
Alias of 'clone' method.
"""
return self.clone()
def deepupdate(self, other, *args):
"""
Alias of 'merge' method.
"""
self.merge(other, *args)
def dump(self, data=None):
"""
Return a readable string representation of any dict/list.
This method can be used both as static method or instance method.
"""
return dict_util.dump(data or self)
def filter(self, predicate):
"""
Return a new filtered dict using the given predicate function.
Predicate function receives key, value arguments and should return a bool value.
"""
return dict_util.filter(self, predicate)
def flatten(self, separator='_'):
"""
Return a new flatten dict using the given separator to concat nested dict keys.
"""
return dict_util.flatten(self, separator)
def invert(self, flat=False):
"""
Return a new inverted dict, where values become keys and keys become values.
Since multiple keys could have the same value, each value will be a list of keys.
If flat is True each value will be a single value (use this only if values are unique).
"""
return dict_util.invert(self, flat)
def items_sorted_by_keys(self, reverse=False):
"""
Return items (key/value list) sorted by keys.
If reverse is True, the list will be reversed.
"""
return dict_util.items_sorted_by_keys(self, reverse=reverse)
def items_sorted_by_values(self, reverse=False):
"""
Return items (key/value list) sorted by values.
If reverse is True, the list will be reversed.
"""
return dict_util.items_sorted_by_values(self, reverse=reverse)
def keypaths(self):
"""
Return a list of all keypaths in the dict.
"""
sep = self._keypath_separator or '.'
return dict_util.keypaths(self, separator=sep)
def merge(self, other, *args):
"""
Merge one or more dict objects into current instance (deepupdate).
Sub-dictionaries will be merged toghether.
"""
dict_util.merge(self, other, *args)
def move(self, key_src, key_dest):
"""
Move a dict instance value item from 'key_src' to 'key_dst'.
It can be used to rename a key.
If key_dst exists, its value will be overwritten.
"""
dict_util.move(self, key_src, key_dest)
def remove(self, keys, *args):
"""
Remove multiple keys from the current dict instance.
It is possible to pass a single key or more keys (as list or *args).
"""
dict_util.remove(self, keys, *args)
def standardize(self):
"""
Standardize all dict keys (e.g. 'Location Latitude' -> 'location_latitude').
"""
dict_util.standardize(self)
def subset(self, keys, *args):
"""
Return a new dict subset for the given keys.
It is possible to pass a single key or multiple keys (as list or *args).
"""
return dict_util.subset(self, keys, *args)
def swap(self, key1, key2):
"""
Swap items values at the given keys.
"""
dict_util.swap(self, key1, key2)
def traverse(self, callback):
"""
Traverse the current dict instance (including nested dicts),
and pass each item (dict, key, value) to the callback function.
"""
dict_util.traverse(self, callback)
def unique(self):
"""
Remove duplicated values from the current dict instance.
"""
dict_util.unique(self)

View File

@ -8,6 +8,9 @@ from six import string_types, text_type
class IODict(dict):
def __init__(self, *args, **kwargs):
"""
Constructs a new instance.
"""
# if first argument is data-string try to decode it.
# use 'format' kwarg to specify the decoder to use, default 'json'.
if len(args) and isinstance(args[0], string_types):
@ -54,57 +57,133 @@ class IODict(dict):
@classmethod
def from_base64(cls, s, subformat='json', encoding='utf-8', **kwargs):
"""
Load and decode Base64 data from url, filepath or data-string.
Data is decoded according to subformat and encoding.
Decoder specific options can be passed using kwargs.
Return a new dict instance. A ValueError is raised in case of failure.
"""
kwargs['subformat'] = subformat
kwargs['encoding'] = encoding
return cls(IODict._decode(s, 'base64', **kwargs))
@classmethod
def from_csv(cls, s, columns=None, columns_row=True, **kwargs):
"""
Load and decode CSV data from url, filepath or data-string.
Decoder specific options can be passed using kwargs: https://docs.python.org/3/library/csv.html
Return a new dict instance. A ValueError is raised in case of failure.
"""
kwargs['columns'] = columns
kwargs['columns_row'] = columns_row
return cls(IODict._decode(s, 'csv', **kwargs))
@classmethod
def from_json(cls, s, **kwargs):
"""
Load and decode JSON data from url, filepath or data-string.
Decoder specific options can be passed using kwargs: https://docs.python.org/3/library/json.html
Return a new dict instance. A ValueError is raised in case of failure.
"""
return cls(IODict._decode(s, 'json', **kwargs))
@classmethod
def from_query_string(cls, s, **kwargs):
"""
Load and decode query-string from url, filepath or data-string.
Return a new dict instance. A ValueError is raised in case of failure.
"""
return cls(IODict._decode(s, 'query_string', **kwargs))
@classmethod
def from_toml(cls, s, **kwargs):
"""
Load and decode TOML data from url, filepath or data-string.
Decoder specific options can be passed using kwargs: https://pypi.org/project/toml/
Return a new dict instance. A ValueError is raised in case of failure.
"""
return cls(IODict._decode(s, 'toml', **kwargs))
@classmethod
def from_xml(cls, s, **kwargs):
"""
Load and decode XML data from url, filepath or data-string.
Decoder specific options can be passed using kwargs: https://github.com/martinblech/xmltodict
Return a new dict instance. A ValueError is raised in case of failure.
"""
return cls(IODict._decode(s, 'xml', **kwargs))
@classmethod
def from_yaml(cls, s, **kwargs):
"""
Load and decode YAML data from url, filepath or data-string.
Decoder specific options can be passed using kwargs: https://pyyaml.org/wiki/PyYAMLDocumentation
Return a new dict instance. A ValueError is raised in case of failure.
"""
return cls(IODict._decode(s, 'yaml', **kwargs))
def to_base64(self, subformat='json', encoding='utf-8', **kwargs):
"""
Encode the current dict instance in Base64 format using the given subformat and encoding.
Encoder specific options can be passed using kwargs.
Return the encoded string and optionally save it at the specified 'filepath'.
A ValueError is raised in case of failure.
"""
kwargs['subformat'] = subformat
kwargs['encoding'] = encoding
return IODict._encode(self, 'base64', **kwargs)
def to_csv(self, key='values', columns=None, columns_row=True, **kwargs):
"""
Encode the current dict instance in CSV format.
Encoder specific options can be passed using kwargs: https://docs.python.org/3/library/csv.html
Return the encoded string and optionally save it at the specified 'filepath'.
A ValueError is raised in case of failure.
"""
kwargs['columns'] = columns
kwargs['columns_row'] = columns_row
return IODict._encode(self[key], 'csv', **kwargs)
def to_json(self, **kwargs):
"""
Encode the current dict instance in JSON format.
Encoder specific options can be passed using kwargs: https://docs.python.org/3/library/json.html
Return the encoded string and optionally save it at the specified 'filepath'.
A ValueError is raised in case of failure.
"""
return IODict._encode(self, 'json', **kwargs)
def to_query_string(self, **kwargs):
"""
Encode the current dict instance in query-string format.
Return the encoded string and optionally save it at the specified 'filepath'.
A ValueError is raised in case of failure.
"""
return IODict._encode(self, 'query_string', **kwargs)
def to_toml(self, **kwargs):
"""
Encode the current dict instance in TOML format.
Encoder specific options can be passed using kwargs: https://pypi.org/project/toml/
Return the encoded string and optionally save it at the specified 'filepath'.
A ValueError is raised in case of failure.
"""
return IODict._encode(self, 'toml', **kwargs)
def to_xml(self, **kwargs):
"""
Encode the current dict instance in XML format.
Encoder specific options can be passed using kwargs: https://github.com/martinblech/xmltodict
Return the encoded string and optionally save it at the specified 'filepath'.
A ValueError is raised in case of failure.
"""
return IODict._encode(self, 'xml', **kwargs)
def to_yaml(self, **kwargs):
"""
Encode the current dict instance in YAML format.
Encoder specific options can be passed using kwargs: https://pyyaml.org/wiki/PyYAMLDocumentation
Return the encoded string and optionally save it at the specified 'filepath'.
A ValueError is raised in case of failure.
"""
return IODict._encode(self, 'yaml', **kwargs)

View File

@ -8,6 +8,9 @@ from six import string_types
class KeypathDict(dict):
def __init__(self, *args, **kwargs):
"""
Constructs a new instance.
"""
self._keypath_separator = kwargs.pop('keypath_separator', '.')
super(KeypathDict, self).__init__(*args, **kwargs)
self._check_keypath_separator_in_keys(self)

View File

@ -8,6 +8,9 @@ from decimal import Decimal
class ParseDict(dict):
def __init__(self, *args, **kwargs):
"""
Constructs a new instance.
"""
super(ParseDict, self).__init__(*args, **kwargs)
def _get_value(self, key, default, options,