dev4py.utils.dicts

The dicts module provides a set of utility functions to simplify dict operations

  1"""
  2The `dicts` module provides a set of utility functions to simplify dict operations
  3"""
  4
  5# Copyright 2022 the original author or authors (i.e.: St4rG00se for Dev4py).
  6#
  7# Licensed under the Apache License, Version 2.0 (the "License");
  8# you may not use this file except in compliance with the License.
  9# You may obtain a copy of the License at
 10#
 11#      https://www.apache.org/licenses/LICENSE-2.0
 12#
 13# Unless required by applicable law or agreed to in writing, software
 14# distributed under the License is distributed on an "AS IS" BASIS,
 15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 16# See the License for the specific language governing permissions and
 17# limitations under the License.
 18
 19from functools import partial
 20from typing import Optional, Any
 21
 22from dev4py.utils.joptional import JOptional
 23from dev4py.utils.objects import non_none, require_non_none, to_none
 24from dev4py.utils.types import K, V, Supplier
 25
 26
 27def is_dict(value: Any) -> bool:
 28    """
 29    If the given value is a dict, returns true, otherwise false
 30
 31    Returns:
 32        bool: true if the given value is a dict, otherwise false
 33    """
 34    return isinstance(value, dict)
 35
 36
 37def _get_value(dictionary: dict[K, V], key: K) -> Optional[V]:
 38    """
 39    private function to replace get_joptional_value lambda
 40    Note: lambda are not used in order to be compatible with multiprocessing (lambda are not serializable)
 41    """
 42    # lambda d: d.get(key)
 43    return dictionary.get(key)
 44
 45
 46def get_joptional_value(dictionary: Optional[dict[K, V]], key: K) -> JOptional[V]:
 47    """
 48    Tries to get a value from a dict with the given key and returns a JOptional describing the result
 49
 50    Args:
 51        dictionary: The dict
 52        key: The key
 53
 54    Returns:
 55        JOptional[V]: An empty JOptional if dictionary is None or the searched key result is None, otherwise a JOptional
 56        with a present value
 57    """
 58    if non_none(dictionary) and not is_dict(dictionary):
 59        raise TypeError("Optional[dict[K, V]] parameter is required")
 60
 61    return JOptional \
 62        .of_noneable(dictionary) \
 63        .map(partial(_get_value, key=key))
 64
 65
 66def get_value(
 67        dictionary: Optional[dict[K, V]], key: K, default_supplier: Supplier[Optional[V]] = to_none
 68) -> Optional[V]:
 69    """
 70    Returns the value from a dict with the given key if presents, otherwise returns the result produced by the supplying
 71    function
 72
 73    Args:
 74        dictionary: The dict
 75        key: The searched key
 76        default_supplier: The supplying function that produces a value to be returned
 77
 78    Returns:
 79        Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary
 80        is None)
 81
 82    """
 83    return get_joptional_value(dictionary, key).or_else_get(default_supplier)
 84
 85
 86def get_value_from_path(
 87        dictionary: Optional[dict[K, Any]], path: list[Any], default_supplier: Supplier[Optional[V]] = to_none
 88) -> Optional[V]:
 89    """
 90    Returns the value from a deep dict (dict of dicts) with the given key path if present, otherwise returns the result
 91    produced by the supplying function
 92
 93    Args:
 94        dictionary: The dict
 95        path: The searched key path
 96        default_supplier: The supplying function that produces a value to be returned
 97
 98    Returns:
 99        Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary
100        is None)
101
102    Raises:
103        TypeError: if dictionary is not None and not a dict
104    """
105    if non_none(dictionary) and not is_dict(dictionary):
106        raise TypeError("Optional[dict[K, V]] dictionary parameter must be a dict or None value")
107
108    if not path:
109        return default_supplier()
110
111    if len(path) == 1:
112        return get_value(dictionary, path[0], default_supplier)
113
114    current_path_value: Any = get_value(dictionary, path[0])
115    return get_value_from_path(
116        current_path_value,
117        path[1:],
118        default_supplier
119    ) if is_dict(current_path_value) else default_supplier()
120
121
122def put_value(dictionary: dict[K, V], key: K, value: V) -> Optional[V]:
123    """
124    Associates the specified value with the specified key in the given map. If the map previously contained a mapping
125    for the key, the old value is returned and replaced by the specified value
126
127    Args:
128        dictionary: The dict
129        key: The key with which the specified value is to be associated
130        value: The value to be associated with the specified key
131
132    Returns:
133        Optional[V]: The previous value associated with key, or None if there was no mapping for key.
134
135    Raises:
136        TypeError: if dictionary is not a dict
137    """
138    if not is_dict(dictionary):
139        raise TypeError("dictionary must be a dict value")
140
141    result: Optional[V] = dictionary.get(key)
142    dictionary[key] = value
143    return result
144
145
146def empty_dict() -> dict[Any, Any]:
147    """
148    Returns an empty dict
149    Returns:
150        dict[Any, Any]: an empty dict
151    """
152    return {}
153
154
155def update(dict_1: dict[K, V], dict_2: dict[K, V]) -> dict[K, V]:
156    """
157    Adds all elements of the second dict to the first one and returns it
158
159    Args:
160        dict_1: The dict where add elements
161        dict_2: The dict with elements to add
162
163    Returns:
164        dict_1 (dict[K, V]): The first dict with added elements from dict_2
165
166    Raises:
167        TypeError: if dict_1 or dict_2 is None
168    """
169    require_non_none(dict_1).update(require_non_none(dict_2))
170    return dict_1
def is_dict(value: Any) -> bool:
28def is_dict(value: Any) -> bool:
29    """
30    If the given value is a dict, returns true, otherwise false
31
32    Returns:
33        bool: true if the given value is a dict, otherwise false
34    """
35    return isinstance(value, dict)

If the given value is a dict, returns true, otherwise false

Returns:

bool: true if the given value is a dict, otherwise false

def get_joptional_value( dictionary: Optional[dict[~K, ~V]], key: ~K) -> dev4py.utils.joptional.JOptional[~V]:
47def get_joptional_value(dictionary: Optional[dict[K, V]], key: K) -> JOptional[V]:
48    """
49    Tries to get a value from a dict with the given key and returns a JOptional describing the result
50
51    Args:
52        dictionary: The dict
53        key: The key
54
55    Returns:
56        JOptional[V]: An empty JOptional if dictionary is None or the searched key result is None, otherwise a JOptional
57        with a present value
58    """
59    if non_none(dictionary) and not is_dict(dictionary):
60        raise TypeError("Optional[dict[K, V]] parameter is required")
61
62    return JOptional \
63        .of_noneable(dictionary) \
64        .map(partial(_get_value, key=key))

Tries to get a value from a dict with the given key and returns a JOptional describing the result

Arguments:
  • dictionary: The dict
  • key: The key
Returns:

JOptional[V]: An empty JOptional if dictionary is None or the searched key result is None, otherwise a JOptional with a present value

def get_value( dictionary: Optional[dict[~K, ~V]], key: ~K, default_supplier: Callable[[], Optional[~V]] = <function to_none>) -> Optional[~V]:
67def get_value(
68        dictionary: Optional[dict[K, V]], key: K, default_supplier: Supplier[Optional[V]] = to_none
69) -> Optional[V]:
70    """
71    Returns the value from a dict with the given key if presents, otherwise returns the result produced by the supplying
72    function
73
74    Args:
75        dictionary: The dict
76        key: The searched key
77        default_supplier: The supplying function that produces a value to be returned
78
79    Returns:
80        Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary
81        is None)
82
83    """
84    return get_joptional_value(dictionary, key).or_else_get(default_supplier)

Returns the value from a dict with the given key if presents, otherwise returns the result produced by the supplying function

Arguments:
  • dictionary: The dict
  • key: The searched key
  • default_supplier: The supplying function that produces a value to be returned
Returns:

Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary is None)

def get_value_from_path( dictionary: Optional[dict[~K, Any]], path: list[typing.Any], default_supplier: Callable[[], Optional[~V]] = <function to_none>) -> Optional[~V]:
 87def get_value_from_path(
 88        dictionary: Optional[dict[K, Any]], path: list[Any], default_supplier: Supplier[Optional[V]] = to_none
 89) -> Optional[V]:
 90    """
 91    Returns the value from a deep dict (dict of dicts) with the given key path if present, otherwise returns the result
 92    produced by the supplying function
 93
 94    Args:
 95        dictionary: The dict
 96        path: The searched key path
 97        default_supplier: The supplying function that produces a value to be returned
 98
 99    Returns:
100        Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary
101        is None)
102
103    Raises:
104        TypeError: if dictionary is not None and not a dict
105    """
106    if non_none(dictionary) and not is_dict(dictionary):
107        raise TypeError("Optional[dict[K, V]] dictionary parameter must be a dict or None value")
108
109    if not path:
110        return default_supplier()
111
112    if len(path) == 1:
113        return get_value(dictionary, path[0], default_supplier)
114
115    current_path_value: Any = get_value(dictionary, path[0])
116    return get_value_from_path(
117        current_path_value,
118        path[1:],
119        default_supplier
120    ) if is_dict(current_path_value) else default_supplier()

Returns the value from a deep dict (dict of dicts) with the given key path if present, otherwise returns the result produced by the supplying function

Arguments:
  • dictionary: The dict
  • path: The searched key path
  • default_supplier: The supplying function that produces a value to be returned
Returns:

Optional[V]: The value, if present, otherwise the result produced by the supplying function (even if dictionary is None)

Raises:
  • TypeError: if dictionary is not None and not a dict
def put_value(dictionary: dict[~K, ~V], key: ~K, value: ~V) -> Optional[~V]:
123def put_value(dictionary: dict[K, V], key: K, value: V) -> Optional[V]:
124    """
125    Associates the specified value with the specified key in the given map. If the map previously contained a mapping
126    for the key, the old value is returned and replaced by the specified value
127
128    Args:
129        dictionary: The dict
130        key: The key with which the specified value is to be associated
131        value: The value to be associated with the specified key
132
133    Returns:
134        Optional[V]: The previous value associated with key, or None if there was no mapping for key.
135
136    Raises:
137        TypeError: if dictionary is not a dict
138    """
139    if not is_dict(dictionary):
140        raise TypeError("dictionary must be a dict value")
141
142    result: Optional[V] = dictionary.get(key)
143    dictionary[key] = value
144    return result

Associates the specified value with the specified key in the given map. If the map previously contained a mapping for the key, the old value is returned and replaced by the specified value

Arguments:
  • dictionary: The dict
  • key: The key with which the specified value is to be associated
  • value: The value to be associated with the specified key
Returns:

Optional[V]: The previous value associated with key, or None if there was no mapping for key.

Raises:
  • TypeError: if dictionary is not a dict
def empty_dict() -> dict[typing.Any, typing.Any]:
147def empty_dict() -> dict[Any, Any]:
148    """
149    Returns an empty dict
150    Returns:
151        dict[Any, Any]: an empty dict
152    """
153    return {}

Returns an empty dict

Returns:

dict[Any, Any]: an empty dict

def update(dict_1: dict[~K, ~V], dict_2: dict[~K, ~V]) -> dict[~K, ~V]:
156def update(dict_1: dict[K, V], dict_2: dict[K, V]) -> dict[K, V]:
157    """
158    Adds all elements of the second dict to the first one and returns it
159
160    Args:
161        dict_1: The dict where add elements
162        dict_2: The dict with elements to add
163
164    Returns:
165        dict_1 (dict[K, V]): The first dict with added elements from dict_2
166
167    Raises:
168        TypeError: if dict_1 or dict_2 is None
169    """
170    require_non_none(dict_1).update(require_non_none(dict_2))
171    return dict_1

Adds all elements of the second dict to the first one and returns it

Arguments:
  • dict_1: The dict where add elements
  • dict_2: The dict with elements to add
Returns:

dict_1 (dict[K, V]): The first dict with added elements from dict_2

Raises:
  • TypeError: if dict_1 or dict_2 is None