File: util.py

package info (click to toggle)
python-rjsmin 1.2.5%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 2,256 kB
  • sloc: javascript: 8,503; python: 5,315; ansic: 821; sh: 100; makefile: 19
file content (276 lines) | stat: -rw-r--r-- 6,208 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# -*- coding: ascii -*-
#
# Copyright 2024 - 2025
# Andr\xe9 Malo or his licensors, as applicable
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Utilities
~~~~~~~~~

"""

import functools as _ft

basestring_ = (
    str
    if str is not bytes
    else basestring  # noqa pylint: disable = undefined-variable
)


def cached(func):
    """
    Caching decorator

    Parameters:
      func (callable):
        The function to cache the result of

    Returns:
        The decorated function
    """
    cache = getattr(_ft, "cache", None)
    if cache is not None:
        return cache(func)

    store = {}

    @_ft.wraps(func)
    def inner(*args, **kwargs):
        """The cache wrapper"""
        key = tuple(list(args) + sorted(kwargs.items()))
        try:
            return store[key]
        except KeyError:
            store[key] = result = func(*args, **kwargs)
            return result

    return inner


def dictmerge(dict1, dict2, resolve_left=None):
    """
    Merge nested dict2 into dict1

    Parameters:
      dict1 (dict or adict):
        Dict to update

      dict2 (dict or adict):
        Dict to merge

      resolve_left (callable):
        A resolver to be called on each callable left-side item. If omitted or
        ``None``, the items will be passed through as-is

    Returns:
      dict or adict: The updated dict1. If it was an adict, a new adict is
                     returned.
    """
    type1 = type(dict1)
    if isinstance(dict2, adict):
        type1 = adict
    elif type1 not in (dict, adict):
        type1 = adict

    if dict1 is None:
        if not isinstance(dict2, (dict, adict)):
            return dict2
        dict1 = {}

    dict1 = dict(dict1.items())
    if resolve_left is not None:
        for key, value in list(dict1.items()):
            if callable(value) and isinstance(dict2.get(key), (adict, dict)):
                dict1[key] = resolve_left(value)

    for key, value in dict2.items():
        if isinstance(value, (dict, adict)):
            value = dictmerge(
                dict1.get(key, {}),
                value,
                resolve_left=resolve_left,
            )
        dict1[key] = value

    return type1(dict1)


class adict(object):
    """attribute dict"""

    # pylint: disable = invalid-name, missing-docstring

    def __init__(self, *args, **kwargs):
        """
        Initialization

        Parameters:
          *args:
            Positional dict args

          **kwargs:
            Keyword dict args
        """
        self.__x__ = dict(*args, **kwargs)

    def __repr__(self):
        """
        Return debug representation

        Returns:
          str: Debug representation
        """
        return "%s(%r)" % (self.__class__.__name__, self.__x__)

    def __bool__(self):
        """
        Return bool value of the object

        Returns:
          bool: False if empty, True otherwise
        """
        return bool(self.__x__)

    __nonzero__ = __bool__

    def __iter__(self):
        """
        Return key iterator

        Returns:
          iterable: New key iterator
        """
        return iter(self.__x__)

    def __getitem__(self, name):
        """
        Get value by subscript

        Parameters:
          name (str):
            The key

        Returns:
          any: The value

        Raises:
          KeyError: Key not found
        """
        return self.__x__[name]

    def __setitem__(self, name, value):
        """
        Set value by subscript

        Parameters:
          name (str):
            The key

          value (any):
            The value
        """
        self.__x__[name] = value

    def __getattr__(self, name):
        """
        Get value for dot notation

        Parameters:
          name (str):
            The key

        Returns:
          any: The value

        Raises:
          AttributeError: Key not found
        """
        if name == "__setstate__":
            raise AttributeError(name)
        try:
            return super(adict, self).__getattr__(name)
        except AttributeError:
            try:
                return self.__x__[name]
            except KeyError:
                raise AttributeError(  # pylint: disable = raise-missing-from
                    name
                )

    def __setattr__(self, name, value):
        """
        Set value with dot notation

        Parameters:
          name (str):
            The key

          value (any):
            The value
        """
        if name == "__x__" or hasattr(self.__class__, name):
            super(adict, self).__setattr__(name, value)
        else:
            self.__x__[name] = value

    def keys(self):
        """
        Create key iterator

        Returns:
          iterable: New key iterator
        """
        return self.__x__.keys()

    def items(self):
        """
        Create key/value iterator

        Returns:
          iterable: New key/value iterator
        """
        return self.__x__.items()

    def get(self, *args, **kwargs):
        """
        Get value with default

        Parameters:
          *args:
            Positional dict.get args

          **kwargs:
            Keyword dict.get args

        Returns:
          any: The value or the default (if the key doesn't exist)
        """
        return self.__x__.get(*args, **kwargs)

    def pop(self, *args, **kwargs):
        """
        Pop value

        Parameters:
          *args:
            Positional dict.pop args

          **kwargs:
            Keyword dict.pop args

        Returns:
          any: The value or the default (if the key doesn't exist)
        """
        return self.__x__.pop(*args, **kwargs)