# Copyright (c) 2006-2017 Andrey Golovigin # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
def new_f(*args, **kwargs): import warnings message = '{0}() is deprecated since {1}'.format(f.__name__, since) if reason: message += ': {0}'.format(reason) warnings.warn(message, DeprecationWarning, stacklevel=2) return f(*args, **kwargs)
memory = {} history = deque()
@wraps(f) def new_f(*args): if args not in memory: if len(history) >= capacity: del memory[history.popleft()] memory[args] = f(*args) history.append(args) return memory[args] return new_f
def new_f(*args, **kwargs): return list(f(*args, **kwargs))
a, b = itertools.tee(iterable) next(b, None) return itertools.zip_longest(a, b)
"""A dict with case-insensitive lookup.
>>> d = CaseInsensitiveDict(TesT='passed') >>> d CaseInsensitiveDict({'TesT': 'passed'}) >>> d.lower() CaseInsensitiveDict({'test': 'passed'}) >>> print(d['TesT']) passed >>> print(d['test']) passed >>> print(d['Test']) passed >>> print(d.get('test')) passed >>> print(d.get('Test')) passed
>>> d['Test'] = 'passed again' >>> print(d['test']) passed again >>> 'test' in d True >>> 'Test' in d True >>> print(list(d.keys())) ['Test'] >>> for key in d: ... print(key) Test >>> for key, value in d.items(): ... print(key, value) Test passed again >>> bool(d) True >>> len(d) 1
>>> del d['test'] >>> len(d) 0 >>> bool(d) False >>> 'test' in d False >>> 'Test' in d False >>> print(d.get('test')) None >>> print(d.get('Test')) None >>> print(d.get('Test', 'failed')) failed
>>> CaseInsensitiveDict( ... (key, value) for key, value in [('a', 'b')] ... ) CaseInsensitiveDict({'a': 'b'})
"""
return len(self._dict)
return iter(list(self._keys.values()))
"""To implement lowercase keys."""
key_lower = key.lower() del self._dict[key_lower] del self._keys[key_lower]
def __repr__(self): """A caselessDict version of __repr__ """ dct = dict((key, self[key]) for key in self) return '{0}({1})'.format( type(self).__name__, repr(dct), )
return ((key.lower(), value) for key, value in self.items())
return type(self)(self.iteritems_lower())
"""CaseInseisitiveDict with default factory, like collections.defaultdict
>>> d = CaseInsensitiveDefaultDict(int) >>> d['a'] 0 >>> d['a'] += 1 >>> d['a'] 1 >>> d['A'] 1 >>> d['a'] = 3 >>> d['a'] 3 >>> d['B'] += 10 >>> d['b'] 10
"""
try: return super(CaseInsensitiveDefaultDict, self).__getitem__(key) except KeyError: return self.default_factory()
""" An (incomplete) ordered case-insensitive dict.
>>> d = OrderedCaseInsensitiveDict([ ... ('Uno', 1), ... ('Dos', 2), ... ('Tres', 3), ... ]) >>> d OrderedCaseInsensitiveDict([('Uno', 1), ('Dos', 2), ('Tres', 3)]) >>> d.lower() OrderedCaseInsensitiveDict([('uno', 1), ('dos', 2), ('tres', 3)]) >>> list(d.keys()) ['Uno', 'Dos', 'Tres'] >>> list(d.items()) [('Uno', 1), ('Dos', 2), ('Tres', 3)] >>> list(d.values()) [1, 2, 3] >>> d['Cuatro'] = 4 >>> list(d.keys()) ['Uno', 'Dos', 'Tres', 'Cuatro'] >>> list(d.items()) [('Uno', 1), ('Dos', 2), ('Tres', 3), ('Cuatro', 4)] >>> list(d.values()) [1, 2, 3, 4] >>> list(d) ['Uno', 'Dos', 'Tres', 'Cuatro'] >>> list(d.keys()) == list(d.keys()) True >>> list(d.values()) == list(d.values()) True >>> list(d.items()) == list(d.items()) True >>> 'Uno' in d True >>> 'uno' in d True >>> d['Uno'] 1 >>> d['uno'] 1 >>> d['UNO'] 1 >>> 'Cuatro' in d True >>> 'CUATRO' in d True >>> d['Cuatro'] 4 >>> d['cuatro'] 4 >>> d['UNO'] = 'one' >>> d['uno'] 'one' >>> d['Uno'] 'one' >>> list(d.keys()) ['Uno', 'Dos', 'Tres', 'Cuatro'] >>> d['cuatro'] = 'four' >>> d['Cuatro'] 'four' >>> d['cuatro'] 'four' >>> list(d.keys()) ['Uno', 'Dos', 'Tres', 'Cuatro']
"""
data = list(data) else:
raise NotImplementedError
return iter(self.order)
""" >>> OrderedCaseInsensitiveDict([('a', 1), ('b', 2)]) == OrderedCaseInsensitiveDict([('a', 1), ('b', 2)]) True >>> OrderedCaseInsensitiveDict([('a', 1), ('b', 2)]) == OrderedCaseInsensitiveDict([('b', 2), ('a', 1)]) False >>> OrderedCaseInsensitiveDict([('a', 1), ('b', 2)]) == dict([('b', 2), ('a', 1)]) True >>> OrderedCaseInsensitiveDict([('a', 1), ('B', 2)]) == OrderedCaseInsensitiveDict([('A', 1), ('b', 2)]) False """ if isinstance(other, (OrderedCaseInsensitiveDict, OrderedDict)): return list(self.items()) == list(other.items()) else: return super(OrderedCaseInsensitiveDict, self).__eq__(other)
return iter(self.order)
for key in self.order: yield self[key]
return [self[key] for key in self.order]
for key in self.order: yield key, self[key]
def __repr__(self): return '{0}({1})'.format( type(self).__name__, repr(list(self.items())) )
"""A very basic case-insensitive set.
>>> s = CaseInsensitiveSet() >>> len(s) 0 >>> 'a' in s False >>> list(CaseInsensitiveSet(['aaa', 'Aaa', 'AAA'])) ['aaa'] >>> s = CaseInsensitiveSet(['Aaa', 'Bbb']) >>> s CaseInsensitiveSet(['Aaa', 'Bbb']) >>> s.lower() CaseInsensitiveSet(['aaa', 'bbb']) >>> len(s) 2 >>> 'aaa' in s True >>> 'Aaa' in s True >>> 'AAA' in s True >>> 'bbb' in s True >>> 'Bbb' in s True >>> 'abc' in s False >>> s.add('ccc') >>> len(s) 3 >>> 'aaa' in s True >>> 'ccc' in s True >>> s.remove('AAA') >>> len(s) 2 >>> 'aaa' in s False
>>> bool(CaseInsensitiveSet(['a'])) True >>> bool(CaseInsensitiveSet([])) False >>> bool(CaseInsensitiveSet()) False
"""
return iter(self._set)
return len(self._set)
def __repr__(self): """A caselessDict version of __repr__ """ return '{0}({1})'.format( type(self).__name__, repr(sorted(self._keys.values())) )
key_lower = key.lower() self._set.discard(key_lower) self._keys.pop(key_lower, None)
return self._keys[key.lower()]
return type(self)(self._set)
|