~ubuntu-branches/ubuntu/wily/openpyxl/wily

« back to all changes in this revision

Viewing changes to openpyxl/compat/odict.py

  • Committer: Package Import Robot
  • Author(s): Yaroslav Halchenko
  • Date: 2015-07-01 10:34:46 UTC
  • mfrom: (1.2.2)
  • Revision ID: package-import@ubuntu.com-20150701103446-y1oktzsnpkukfv5u
Tags: 2.3.0~b1-1
* Fresh upstream beta-release
* debian/copyright -- fixups
* debian/watch - allow to update for alpha/beta releases
* debian/patches
  - up_python3_print - fix for compatibility with python3 (Closes: #790754)
  - deb_no_et_xml_file - there is no et_xmlfile package yet and it
    is optional anyways. Disable it in setup.py so dh*-python magic doesn't
    add unsatisfyiable depends
* debian/control
  - to play safe care only about python >= 2.6
* debian/rules
  - adjust path to changes.rst

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (c) 2001-2011 Python Software Foundation
 
2
#               2011 Raymond Hettinger
 
3
# License: PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
 
4
#          See http://www.opensource.org/licenses/Python-2.0 for full terms
 
5
# Note: backport changes by Raymond were originally distributed under MIT
 
6
#       license, but since the original license for Python is more
 
7
#       restrictive than MIT, code cannot be released under its terms and
 
8
#       still adheres to the limitations of Python license.
 
9
 
 
10
# # {{{ http://code.activestate.com/recipes/576693/ (r9)
 
11
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
 
12
# Passes Python2.7's test suite and incorporates all the latest updates.
 
13
 
 
14
try:
 
15
    from thread import get_ident as _get_ident
 
16
except ImportError:
 
17
    from dummy_thread import get_ident as _get_ident
 
18
 
 
19
try:
 
20
    from _abcoll import KeysView, ValuesView, ItemsView
 
21
except ImportError:
 
22
    pass
 
23
 
 
24
 
 
25
class OrderedDict(dict):
 
26
    'Dictionary that remembers insertion order'
 
27
    # An inherited dict maps keys to values.
 
28
    # The inherited dict provides __getitem__, __len__, __contains__, and get.
 
29
    # The remaining methods are order-aware.
 
30
    # Big-O running times for all methods are the same as for regular dictionaries.
 
31
 
 
32
    # The internal self.__map dictionary maps keys to links in a doubly linked list.
 
33
    # The circular doubly linked list starts and ends with a sentinel element.
 
34
    # The sentinel element never gets deleted (this simplifies the algorithm).
 
35
    # Each link is stored as a list of length three:  [PREV, NEXT, KEY].
 
36
 
 
37
    def __init__(self, *args, **kwds):
 
38
        '''Initialize an ordered dictionary.  Signature is the same as for
 
39
        regular dictionaries, but keyword arguments are not recommended
 
40
        because their insertion order is arbitrary.
 
41
 
 
42
        '''
 
43
        if len(args) > 1:
 
44
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
 
45
        try:
 
46
            self.__root
 
47
        except AttributeError:
 
48
            self.__root = root = []  # sentinel node
 
49
            root[:] = [root, root, None]
 
50
            self.__map = {}
 
51
        self.__update(*args, **kwds)
 
52
 
 
53
    def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
 
54
        'od.__setitem__(i, y) <==> od[i]=y'
 
55
        # Setting a new item creates a new link which goes at the end of the linked
 
56
        # list, and the inherited dictionary is updated with the new key/value pair.
 
57
        if key not in self:
 
58
            root = self.__root
 
59
            last = root[0]
 
60
            last[1] = root[0] = self.__map[key] = [last, root, key]
 
61
        dict_setitem(self, key, value)
 
62
 
 
63
    def __delitem__(self, key, dict_delitem=dict.__delitem__):
 
64
        'od.__delitem__(y) <==> del od[y]'
 
65
        # Deleting an existing item uses self.__map to find the link which is
 
66
        # then removed by updating the links in the predecessor and successor nodes.
 
67
        dict_delitem(self, key)
 
68
        link_prev, link_next, key = self.__map.pop(key)
 
69
        link_prev[1] = link_next
 
70
        link_next[0] = link_prev
 
71
 
 
72
    def __iter__(self):
 
73
        'od.__iter__() <==> iter(od)'
 
74
        root = self.__root
 
75
        curr = root[1]
 
76
        while curr is not root:
 
77
            yield curr[2]
 
78
            curr = curr[1]
 
79
 
 
80
    def __reversed__(self):
 
81
        'od.__reversed__() <==> reversed(od)'
 
82
        root = self.__root
 
83
        curr = root[0]
 
84
        while curr is not root:
 
85
            yield curr[2]
 
86
            curr = curr[0]
 
87
 
 
88
    def clear(self):
 
89
        'od.clear() -> None.  Remove all items from od.'
 
90
        try:
 
91
            for node in self.__map.itervalues():
 
92
                del node[:]
 
93
            root = self.__root
 
94
            root[:] = [root, root, None]
 
95
            self.__map.clear()
 
96
        except AttributeError:
 
97
            pass
 
98
        dict.clear(self)
 
99
 
 
100
    def popitem(self, last=True):
 
101
        '''od.popitem() -> (k, v), return and remove a (key, value) pair.
 
102
        Pairs are returned in LIFO order if last is true or FIFO order if false.
 
103
 
 
104
        '''
 
105
        if not self:
 
106
            raise KeyError('dictionary is empty')
 
107
        root = self.__root
 
108
        if last:
 
109
            link = root[0]
 
110
            link_prev = link[0]
 
111
            link_prev[1] = root
 
112
            root[0] = link_prev
 
113
        else:
 
114
            link = root[1]
 
115
            link_next = link[1]
 
116
            root[1] = link_next
 
117
            link_next[0] = root
 
118
        key = link[2]
 
119
        del self.__map[key]
 
120
        value = dict.pop(self, key)
 
121
        return key, value
 
122
 
 
123
    # -- the following methods do not depend on the internal structure --
 
124
 
 
125
    def keys(self):
 
126
        'od.keys() -> list of keys in od'
 
127
        return list(self)
 
128
 
 
129
    def values(self):
 
130
        'od.values() -> list of values in od'
 
131
        return [self[key] for key in self]
 
132
 
 
133
    def items(self):
 
134
        'od.items() -> list of (key, value) pairs in od'
 
135
        return [(key, self[key]) for key in self]
 
136
 
 
137
    def iterkeys(self):
 
138
        'od.iterkeys() -> an iterator over the keys in od'
 
139
        return iter(self)
 
140
 
 
141
    def itervalues(self):
 
142
        'od.itervalues -> an iterator over the values in od'
 
143
        for k in self:
 
144
            yield self[k]
 
145
 
 
146
    def iteritems(self):
 
147
        'od.iteritems -> an iterator over the (key, value) items in od'
 
148
        for k in self:
 
149
            yield (k, self[k])
 
150
 
 
151
    def update(*args, **kwds):
 
152
        '''od.update(E, **F) -> None.  Update od from dict/iterable E and F.
 
153
 
 
154
        If E is a dict instance, does:           for k in E: od[k] = E[k]
 
155
        If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]
 
156
        Or if E is an iterable of items, does:   for k, v in E: od[k] = v
 
157
        In either case, this is followed by:     for k, v in F.items(): od[k] = v
 
158
 
 
159
        '''
 
160
        if len(args) > 2:
 
161
            raise TypeError('update() takes at most 2 positional '
 
162
                            'arguments (%d given)' % (len(args),))
 
163
        elif not args:
 
164
            raise TypeError('update() takes at least 1 argument (0 given)')
 
165
        self = args[0]
 
166
        # Make progressively weaker assumptions about "other"
 
167
        other = ()
 
168
        if len(args) == 2:
 
169
            other = args[1]
 
170
        if isinstance(other, dict):
 
171
            for key in other:
 
172
                self[key] = other[key]
 
173
        elif hasattr(other, 'keys'):
 
174
            for key in other.keys():
 
175
                self[key] = other[key]
 
176
        else:
 
177
            for key, value in other:
 
178
                self[key] = value
 
179
        for key, value in kwds.items():
 
180
            self[key] = value
 
181
 
 
182
    __update = update  # let subclasses override update without breaking __init__
 
183
 
 
184
    __marker = object()
 
185
 
 
186
    def pop(self, key, default=__marker):
 
187
        '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 
188
        If key is not found, d is returned if given, otherwise KeyError is raised.
 
189
 
 
190
        '''
 
191
        if key in self:
 
192
            result = self[key]
 
193
            del self[key]
 
194
            return result
 
195
        if default is self.__marker:
 
196
            raise KeyError(key)
 
197
        return default
 
198
 
 
199
    def setdefault(self, key, default=None):
 
200
        'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
 
201
        if key in self:
 
202
            return self[key]
 
203
        self[key] = default
 
204
        return default
 
205
 
 
206
    def __repr__(self, _repr_running={}):
 
207
        'od.__repr__() <==> repr(od)'
 
208
        call_key = id(self), _get_ident()
 
209
        if call_key in _repr_running:
 
210
            return '...'
 
211
        _repr_running[call_key] = 1
 
212
        try:
 
213
            if not self:
 
214
                return '%s()' % (self.__class__.__name__,)
 
215
            return '%s(%r)' % (self.__class__.__name__, self.items())
 
216
        finally:
 
217
            del _repr_running[call_key]
 
218
 
 
219
    def __reduce__(self):
 
220
        'Return state information for pickling'
 
221
        items = [[k, self[k]] for k in self]
 
222
        inst_dict = vars(self).copy()
 
223
        for k in vars(OrderedDict()):
 
224
            inst_dict.pop(k, None)
 
225
        if inst_dict:
 
226
            return (self.__class__, (items,), inst_dict)
 
227
        return self.__class__, (items,)
 
228
 
 
229
    def copy(self):
 
230
        'od.copy() -> a shallow copy of od'
 
231
        return self.__class__(self)
 
232
 
 
233
    @classmethod
 
234
    def fromkeys(cls, iterable, value=None):
 
235
        '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
 
236
        and values equal to v (which defaults to None).
 
237
 
 
238
        '''
 
239
        d = cls()
 
240
        for key in iterable:
 
241
            d[key] = value
 
242
        return d
 
243
 
 
244
    def __eq__(self, other):
 
245
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
 
246
        while comparison to a regular mapping is order-insensitive.
 
247
 
 
248
        '''
 
249
        if isinstance(other, OrderedDict):
 
250
            return len(self) == len(other) and self.items() == other.items()
 
251
        return dict.__eq__(self, other)
 
252
 
 
253
    def __ne__(self, other):
 
254
        return not self == other
 
255
 
 
256
    # -- the following methods are only used in Python 2.7 --
 
257
 
 
258
    def viewkeys(self):
 
259
        "od.viewkeys() -> a set-like object providing a view on od's keys"
 
260
        return KeysView(self)
 
261
 
 
262
    def viewvalues(self):
 
263
        "od.viewvalues() -> an object providing a view on od's values"
 
264
        return ValuesView(self)
 
265
 
 
266
    def viewitems(self):
 
267
        "od.viewitems() -> a set-like object providing a view on od's items"
 
268
        return ItemsView(self)
 
269
# # end of http://code.activestate.com/recipes/576693/ }}}