File: loose.py

package info (click to toggle)
python-rebulk 3.3.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 752 kB
  • sloc: python: 7,497; makefile: 3
file content (242 lines) | stat: -rw-r--r-- 6,695 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Various utilities functions
"""

import sys

from inspect import isclass
try:
    from inspect import getfullargspec as getargspec

    _FULLARGSPEC_SUPPORTED = True
except ImportError:
    _FULLARGSPEC_SUPPORTED = False
    from inspect import getargspec

from .utils import is_iterable

if sys.version_info < (3, 4, 0):  # pragma: no cover
    def _constructor(class_):
        """
        Retrieves constructor from given class

        :param class_:
        :type class_: class
        :return: constructor from given class
        :rtype: callable
        """
        return class_.__init__
else:  # pragma: no cover
    def _constructor(class_):
        """
        Retrieves constructor from given class

        :param class_:
        :type class_: class
        :return: constructor from given class
        :rtype: callable
        """
        return class_


def call(function, *args, **kwargs):
    """
    Call a function or constructor with given args and kwargs after removing args and kwargs that doesn't match
    function or constructor signature

    :param function: Function or constructor to call
    :type function: callable
    :param args:
    :type args:
    :param kwargs:
    :type kwargs:
    :return: sale vakye as default function call
    :rtype: object
    """
    func = constructor_args if isclass(function) else function_args
    call_args, call_kwargs = func(function, *args, ignore_unused=True, **kwargs)  # @see #20
    return function(*call_args, **call_kwargs)


def function_args(callable_, *args, **kwargs):
    """
    Return (args, kwargs) matching the function signature

    :param callable: callable to inspect
    :type callable: callable
    :param args:
    :type args:
    :param kwargs:
    :type kwargs:
    :return: (args, kwargs) matching the function signature
    :rtype: tuple
    """
    argspec = getargspec(callable_)  # pylint:disable=deprecated-method
    return argspec_args(argspec, False, *args, **kwargs)


def constructor_args(class_, *args, **kwargs):
    """
    Return (args, kwargs) matching the function signature

    :param callable: callable to inspect
    :type callable: Callable
    :param args:
    :type args:
    :param kwargs:
    :type kwargs:
    :return: (args, kwargs) matching the function signature
    :rtype: tuple
    """
    argspec = getargspec(_constructor(class_))  # pylint:disable=deprecated-method
    return argspec_args(argspec, True, *args, **kwargs)


def argspec_args(argspec, constructor, *args, **kwargs):
    """
    Return (args, kwargs) matching the argspec object

    :param argspec: argspec to use
    :type argspec: argspec
    :param constructor: is it a constructor ?
    :type constructor: bool
    :param args:
    :type args:
    :param kwargs:
    :type kwargs:
    :return: (args, kwargs) matching the function signature
    :rtype: tuple
    """
    if argspec.varkw:
        call_kwarg = kwargs
    else:
        call_kwarg = dict((k, kwargs[k]) for k in kwargs if k in argspec.args) # pylint:disable=consider-using-dict-items
    if argspec.varargs:
        call_args = args
    else:
        call_args = args[:len(argspec.args) - (1 if constructor else 0)]
    return call_args, call_kwarg


if not _FULLARGSPEC_SUPPORTED:
    def argspec_args_legacy(argspec, constructor, *args, **kwargs):
        """
        Return (args, kwargs) matching the argspec object

        :param argspec: argspec to use
        :type argspec: argspec
        :param constructor: is it a constructor ?
        :type constructor: bool
        :param args:
        :type args:
        :param kwargs:
        :type kwargs:
        :return: (args, kwargs) matching the function signature
        :rtype: tuple
        """
        if argspec.keywords:
            call_kwarg = kwargs
        else:
            call_kwarg = dict((k, kwargs[k]) for k in kwargs if k in argspec.args) # pylint:disable=consider-using-dict-items
        if argspec.varargs:
            call_args = args
        else:
            call_args = args[:len(argspec.args) - (1 if constructor else 0)]
        return call_args, call_kwarg


    argspec_args = argspec_args_legacy


def ensure_list(param):
    """
    Retrieves a list from given parameter.

    :param param:
    :type param:
    :return:
    :rtype:
    """
    if not param:
        param = []
    elif not is_iterable(param):
        param = [param]
    return param


def ensure_dict(param, default_value, default_key=None):
    """
    Retrieves a dict and a default value from given parameter.

    if parameter is not a dict, it will be promoted as the default value.

    :param param:
    :type param:
    :param default_value:
    :type default_value:
    :param default_key:
    :type default_key:
    :return:
    :rtype:
    """
    if not param:
        param = default_value
    if not isinstance(param, dict):
        if param:
            default_value = param
        return {default_key: param}, default_value
    return param, default_value


def filter_index(collection, predicate=None, index=None):
    """
    Filter collection with predicate function and index.

    If index is not found, returns None.
    :param collection:
    :type collection: collection supporting iteration and slicing
    :param predicate: function to filter the collection with
    :type predicate: function
    :param index: position of a single element to retrieve
    :type index: int
    :return: filtered list, or single element of filtered list if index is defined
    :rtype: list or object
    """
    if index is None and isinstance(predicate, int):
        index = predicate
        predicate = None
    if predicate:
        collection = collection.__class__(filter(predicate, collection))
    if index is not None:
        try:
            collection = collection[index]
        except IndexError:
            collection = None
    return collection


def set_defaults(defaults, kwargs, override=False):
    """
    Set defaults from defaults dict to kwargs dict

    :param override:
    :type override:
    :param defaults:
    :type defaults:
    :param kwargs:
    :type kwargs:
    :return:
    :rtype:
    """
    if 'clear' in defaults.keys() and defaults.pop('clear'):
        kwargs.clear()
    for key, value in defaults.items():
        if key in kwargs:
            if isinstance(value, list) and isinstance(kwargs[key], list):
                kwargs[key] = list(value) + kwargs[key]
            elif isinstance(value, dict) and isinstance(kwargs[key], dict):
                set_defaults(value, kwargs[key])
        if key not in kwargs or override:
            kwargs[key] = value