Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ExeBy/smexe_ro.../usr/lib64/python3....
File: functools.py
"""functools.py - Tools for working with functions and callable objects
[0] Fix | Delete
"""
[1] Fix | Delete
# Python module wrapper for _functools C module
[2] Fix | Delete
# to allow utilities written in Python to be added
[3] Fix | Delete
# to the functools module.
[4] Fix | Delete
# Written by Nick Coghlan <ncoghlan at gmail.com>,
[5] Fix | Delete
# Raymond Hettinger <python at rcn.com>,
[6] Fix | Delete
# and Ɓukasz Langa <lukasz at langa.pl>.
[7] Fix | Delete
# Copyright (C) 2006-2013 Python Software Foundation.
[8] Fix | Delete
# See C source code for _functools credits/copyright
[9] Fix | Delete
[10] Fix | Delete
__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
[11] Fix | Delete
'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial',
[12] Fix | Delete
'partialmethod', 'singledispatch']
[13] Fix | Delete
[14] Fix | Delete
try:
[15] Fix | Delete
from _functools import reduce
[16] Fix | Delete
except ImportError:
[17] Fix | Delete
pass
[18] Fix | Delete
from abc import get_cache_token
[19] Fix | Delete
from collections import namedtuple
[20] Fix | Delete
from types import MappingProxyType
[21] Fix | Delete
from weakref import WeakKeyDictionary
[22] Fix | Delete
from reprlib import recursive_repr
[23] Fix | Delete
try:
[24] Fix | Delete
from _thread import RLock
[25] Fix | Delete
except ImportError:
[26] Fix | Delete
class RLock:
[27] Fix | Delete
'Dummy reentrant lock for builds without threads'
[28] Fix | Delete
def __enter__(self): pass
[29] Fix | Delete
def __exit__(self, exctype, excinst, exctb): pass
[30] Fix | Delete
[31] Fix | Delete
[32] Fix | Delete
################################################################################
[33] Fix | Delete
### update_wrapper() and wraps() decorator
[34] Fix | Delete
################################################################################
[35] Fix | Delete
[36] Fix | Delete
# update_wrapper() and wraps() are tools to help write
[37] Fix | Delete
# wrapper functions that can handle naive introspection
[38] Fix | Delete
[39] Fix | Delete
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
[40] Fix | Delete
'__annotations__')
[41] Fix | Delete
WRAPPER_UPDATES = ('__dict__',)
[42] Fix | Delete
def update_wrapper(wrapper,
[43] Fix | Delete
wrapped,
[44] Fix | Delete
assigned = WRAPPER_ASSIGNMENTS,
[45] Fix | Delete
updated = WRAPPER_UPDATES):
[46] Fix | Delete
"""Update a wrapper function to look like the wrapped function
[47] Fix | Delete
[48] Fix | Delete
wrapper is the function to be updated
[49] Fix | Delete
wrapped is the original function
[50] Fix | Delete
assigned is a tuple naming the attributes assigned directly
[51] Fix | Delete
from the wrapped function to the wrapper function (defaults to
[52] Fix | Delete
functools.WRAPPER_ASSIGNMENTS)
[53] Fix | Delete
updated is a tuple naming the attributes of the wrapper that
[54] Fix | Delete
are updated with the corresponding attribute from the wrapped
[55] Fix | Delete
function (defaults to functools.WRAPPER_UPDATES)
[56] Fix | Delete
"""
[57] Fix | Delete
for attr in assigned:
[58] Fix | Delete
try:
[59] Fix | Delete
value = getattr(wrapped, attr)
[60] Fix | Delete
except AttributeError:
[61] Fix | Delete
pass
[62] Fix | Delete
else:
[63] Fix | Delete
setattr(wrapper, attr, value)
[64] Fix | Delete
for attr in updated:
[65] Fix | Delete
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
[66] Fix | Delete
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
[67] Fix | Delete
# from the wrapped function when updating __dict__
[68] Fix | Delete
wrapper.__wrapped__ = wrapped
[69] Fix | Delete
# Return the wrapper so this can be used as a decorator via partial()
[70] Fix | Delete
return wrapper
[71] Fix | Delete
[72] Fix | Delete
def wraps(wrapped,
[73] Fix | Delete
assigned = WRAPPER_ASSIGNMENTS,
[74] Fix | Delete
updated = WRAPPER_UPDATES):
[75] Fix | Delete
"""Decorator factory to apply update_wrapper() to a wrapper function
[76] Fix | Delete
[77] Fix | Delete
Returns a decorator that invokes update_wrapper() with the decorated
[78] Fix | Delete
function as the wrapper argument and the arguments to wraps() as the
[79] Fix | Delete
remaining arguments. Default arguments are as for update_wrapper().
[80] Fix | Delete
This is a convenience function to simplify applying partial() to
[81] Fix | Delete
update_wrapper().
[82] Fix | Delete
"""
[83] Fix | Delete
return partial(update_wrapper, wrapped=wrapped,
[84] Fix | Delete
assigned=assigned, updated=updated)
[85] Fix | Delete
[86] Fix | Delete
[87] Fix | Delete
################################################################################
[88] Fix | Delete
### total_ordering class decorator
[89] Fix | Delete
################################################################################
[90] Fix | Delete
[91] Fix | Delete
# The total ordering functions all invoke the root magic method directly
[92] Fix | Delete
# rather than using the corresponding operator. This avoids possible
[93] Fix | Delete
# infinite recursion that could occur when the operator dispatch logic
[94] Fix | Delete
# detects a NotImplemented result and then calls a reflected method.
[95] Fix | Delete
[96] Fix | Delete
def _gt_from_lt(self, other, NotImplemented=NotImplemented):
[97] Fix | Delete
'Return a > b. Computed by @total_ordering from (not a < b) and (a != b).'
[98] Fix | Delete
op_result = self.__lt__(other)
[99] Fix | Delete
if op_result is NotImplemented:
[100] Fix | Delete
return op_result
[101] Fix | Delete
return not op_result and self != other
[102] Fix | Delete
[103] Fix | Delete
def _le_from_lt(self, other, NotImplemented=NotImplemented):
[104] Fix | Delete
'Return a <= b. Computed by @total_ordering from (a < b) or (a == b).'
[105] Fix | Delete
op_result = self.__lt__(other)
[106] Fix | Delete
return op_result or self == other
[107] Fix | Delete
[108] Fix | Delete
def _ge_from_lt(self, other, NotImplemented=NotImplemented):
[109] Fix | Delete
'Return a >= b. Computed by @total_ordering from (not a < b).'
[110] Fix | Delete
op_result = self.__lt__(other)
[111] Fix | Delete
if op_result is NotImplemented:
[112] Fix | Delete
return op_result
[113] Fix | Delete
return not op_result
[114] Fix | Delete
[115] Fix | Delete
def _ge_from_le(self, other, NotImplemented=NotImplemented):
[116] Fix | Delete
'Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).'
[117] Fix | Delete
op_result = self.__le__(other)
[118] Fix | Delete
if op_result is NotImplemented:
[119] Fix | Delete
return op_result
[120] Fix | Delete
return not op_result or self == other
[121] Fix | Delete
[122] Fix | Delete
def _lt_from_le(self, other, NotImplemented=NotImplemented):
[123] Fix | Delete
'Return a < b. Computed by @total_ordering from (a <= b) and (a != b).'
[124] Fix | Delete
op_result = self.__le__(other)
[125] Fix | Delete
if op_result is NotImplemented:
[126] Fix | Delete
return op_result
[127] Fix | Delete
return op_result and self != other
[128] Fix | Delete
[129] Fix | Delete
def _gt_from_le(self, other, NotImplemented=NotImplemented):
[130] Fix | Delete
'Return a > b. Computed by @total_ordering from (not a <= b).'
[131] Fix | Delete
op_result = self.__le__(other)
[132] Fix | Delete
if op_result is NotImplemented:
[133] Fix | Delete
return op_result
[134] Fix | Delete
return not op_result
[135] Fix | Delete
[136] Fix | Delete
def _lt_from_gt(self, other, NotImplemented=NotImplemented):
[137] Fix | Delete
'Return a < b. Computed by @total_ordering from (not a > b) and (a != b).'
[138] Fix | Delete
op_result = self.__gt__(other)
[139] Fix | Delete
if op_result is NotImplemented:
[140] Fix | Delete
return op_result
[141] Fix | Delete
return not op_result and self != other
[142] Fix | Delete
[143] Fix | Delete
def _ge_from_gt(self, other, NotImplemented=NotImplemented):
[144] Fix | Delete
'Return a >= b. Computed by @total_ordering from (a > b) or (a == b).'
[145] Fix | Delete
op_result = self.__gt__(other)
[146] Fix | Delete
return op_result or self == other
[147] Fix | Delete
[148] Fix | Delete
def _le_from_gt(self, other, NotImplemented=NotImplemented):
[149] Fix | Delete
'Return a <= b. Computed by @total_ordering from (not a > b).'
[150] Fix | Delete
op_result = self.__gt__(other)
[151] Fix | Delete
if op_result is NotImplemented:
[152] Fix | Delete
return op_result
[153] Fix | Delete
return not op_result
[154] Fix | Delete
[155] Fix | Delete
def _le_from_ge(self, other, NotImplemented=NotImplemented):
[156] Fix | Delete
'Return a <= b. Computed by @total_ordering from (not a >= b) or (a == b).'
[157] Fix | Delete
op_result = self.__ge__(other)
[158] Fix | Delete
if op_result is NotImplemented:
[159] Fix | Delete
return op_result
[160] Fix | Delete
return not op_result or self == other
[161] Fix | Delete
[162] Fix | Delete
def _gt_from_ge(self, other, NotImplemented=NotImplemented):
[163] Fix | Delete
'Return a > b. Computed by @total_ordering from (a >= b) and (a != b).'
[164] Fix | Delete
op_result = self.__ge__(other)
[165] Fix | Delete
if op_result is NotImplemented:
[166] Fix | Delete
return op_result
[167] Fix | Delete
return op_result and self != other
[168] Fix | Delete
[169] Fix | Delete
def _lt_from_ge(self, other, NotImplemented=NotImplemented):
[170] Fix | Delete
'Return a < b. Computed by @total_ordering from (not a >= b).'
[171] Fix | Delete
op_result = self.__ge__(other)
[172] Fix | Delete
if op_result is NotImplemented:
[173] Fix | Delete
return op_result
[174] Fix | Delete
return not op_result
[175] Fix | Delete
[176] Fix | Delete
_convert = {
[177] Fix | Delete
'__lt__': [('__gt__', _gt_from_lt),
[178] Fix | Delete
('__le__', _le_from_lt),
[179] Fix | Delete
('__ge__', _ge_from_lt)],
[180] Fix | Delete
'__le__': [('__ge__', _ge_from_le),
[181] Fix | Delete
('__lt__', _lt_from_le),
[182] Fix | Delete
('__gt__', _gt_from_le)],
[183] Fix | Delete
'__gt__': [('__lt__', _lt_from_gt),
[184] Fix | Delete
('__ge__', _ge_from_gt),
[185] Fix | Delete
('__le__', _le_from_gt)],
[186] Fix | Delete
'__ge__': [('__le__', _le_from_ge),
[187] Fix | Delete
('__gt__', _gt_from_ge),
[188] Fix | Delete
('__lt__', _lt_from_ge)]
[189] Fix | Delete
}
[190] Fix | Delete
[191] Fix | Delete
def total_ordering(cls):
[192] Fix | Delete
"""Class decorator that fills in missing ordering methods"""
[193] Fix | Delete
# Find user-defined comparisons (not those inherited from object).
[194] Fix | Delete
roots = [op for op in _convert if getattr(cls, op, None) is not getattr(object, op, None)]
[195] Fix | Delete
if not roots:
[196] Fix | Delete
raise ValueError('must define at least one ordering operation: < > <= >=')
[197] Fix | Delete
root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
[198] Fix | Delete
for opname, opfunc in _convert[root]:
[199] Fix | Delete
if opname not in roots:
[200] Fix | Delete
opfunc.__name__ = opname
[201] Fix | Delete
setattr(cls, opname, opfunc)
[202] Fix | Delete
return cls
[203] Fix | Delete
[204] Fix | Delete
[205] Fix | Delete
################################################################################
[206] Fix | Delete
### cmp_to_key() function converter
[207] Fix | Delete
################################################################################
[208] Fix | Delete
[209] Fix | Delete
def cmp_to_key(mycmp):
[210] Fix | Delete
"""Convert a cmp= function into a key= function"""
[211] Fix | Delete
class K(object):
[212] Fix | Delete
__slots__ = ['obj']
[213] Fix | Delete
def __init__(self, obj):
[214] Fix | Delete
self.obj = obj
[215] Fix | Delete
def __lt__(self, other):
[216] Fix | Delete
return mycmp(self.obj, other.obj) < 0
[217] Fix | Delete
def __gt__(self, other):
[218] Fix | Delete
return mycmp(self.obj, other.obj) > 0
[219] Fix | Delete
def __eq__(self, other):
[220] Fix | Delete
return mycmp(self.obj, other.obj) == 0
[221] Fix | Delete
def __le__(self, other):
[222] Fix | Delete
return mycmp(self.obj, other.obj) <= 0
[223] Fix | Delete
def __ge__(self, other):
[224] Fix | Delete
return mycmp(self.obj, other.obj) >= 0
[225] Fix | Delete
__hash__ = None
[226] Fix | Delete
return K
[227] Fix | Delete
[228] Fix | Delete
try:
[229] Fix | Delete
from _functools import cmp_to_key
[230] Fix | Delete
except ImportError:
[231] Fix | Delete
pass
[232] Fix | Delete
[233] Fix | Delete
[234] Fix | Delete
################################################################################
[235] Fix | Delete
### partial() argument application
[236] Fix | Delete
################################################################################
[237] Fix | Delete
[238] Fix | Delete
# Purely functional, no descriptor behaviour
[239] Fix | Delete
class partial:
[240] Fix | Delete
"""New function with partial application of the given arguments
[241] Fix | Delete
and keywords.
[242] Fix | Delete
"""
[243] Fix | Delete
[244] Fix | Delete
__slots__ = "func", "args", "keywords", "__dict__", "__weakref__"
[245] Fix | Delete
[246] Fix | Delete
def __new__(*args, **keywords):
[247] Fix | Delete
if not args:
[248] Fix | Delete
raise TypeError("descriptor '__new__' of partial needs an argument")
[249] Fix | Delete
if len(args) < 2:
[250] Fix | Delete
raise TypeError("type 'partial' takes at least one argument")
[251] Fix | Delete
cls, func, *args = args
[252] Fix | Delete
if not callable(func):
[253] Fix | Delete
raise TypeError("the first argument must be callable")
[254] Fix | Delete
args = tuple(args)
[255] Fix | Delete
[256] Fix | Delete
if hasattr(func, "func"):
[257] Fix | Delete
args = func.args + args
[258] Fix | Delete
tmpkw = func.keywords.copy()
[259] Fix | Delete
tmpkw.update(keywords)
[260] Fix | Delete
keywords = tmpkw
[261] Fix | Delete
del tmpkw
[262] Fix | Delete
func = func.func
[263] Fix | Delete
[264] Fix | Delete
self = super(partial, cls).__new__(cls)
[265] Fix | Delete
[266] Fix | Delete
self.func = func
[267] Fix | Delete
self.args = args
[268] Fix | Delete
self.keywords = keywords
[269] Fix | Delete
return self
[270] Fix | Delete
[271] Fix | Delete
def __call__(*args, **keywords):
[272] Fix | Delete
if not args:
[273] Fix | Delete
raise TypeError("descriptor '__call__' of partial needs an argument")
[274] Fix | Delete
self, *args = args
[275] Fix | Delete
newkeywords = self.keywords.copy()
[276] Fix | Delete
newkeywords.update(keywords)
[277] Fix | Delete
return self.func(*self.args, *args, **newkeywords)
[278] Fix | Delete
[279] Fix | Delete
@recursive_repr()
[280] Fix | Delete
def __repr__(self):
[281] Fix | Delete
qualname = type(self).__qualname__
[282] Fix | Delete
args = [repr(self.func)]
[283] Fix | Delete
args.extend(repr(x) for x in self.args)
[284] Fix | Delete
args.extend(f"{k}={v!r}" for (k, v) in self.keywords.items())
[285] Fix | Delete
if type(self).__module__ == "functools":
[286] Fix | Delete
return f"functools.{qualname}({', '.join(args)})"
[287] Fix | Delete
return f"{qualname}({', '.join(args)})"
[288] Fix | Delete
[289] Fix | Delete
def __reduce__(self):
[290] Fix | Delete
return type(self), (self.func,), (self.func, self.args,
[291] Fix | Delete
self.keywords or None, self.__dict__ or None)
[292] Fix | Delete
[293] Fix | Delete
def __setstate__(self, state):
[294] Fix | Delete
if not isinstance(state, tuple):
[295] Fix | Delete
raise TypeError("argument to __setstate__ must be a tuple")
[296] Fix | Delete
if len(state) != 4:
[297] Fix | Delete
raise TypeError(f"expected 4 items in state, got {len(state)}")
[298] Fix | Delete
func, args, kwds, namespace = state
[299] Fix | Delete
if (not callable(func) or not isinstance(args, tuple) or
[300] Fix | Delete
(kwds is not None and not isinstance(kwds, dict)) or
[301] Fix | Delete
(namespace is not None and not isinstance(namespace, dict))):
[302] Fix | Delete
raise TypeError("invalid partial state")
[303] Fix | Delete
[304] Fix | Delete
args = tuple(args) # just in case it's a subclass
[305] Fix | Delete
if kwds is None:
[306] Fix | Delete
kwds = {}
[307] Fix | Delete
elif type(kwds) is not dict: # XXX does it need to be *exactly* dict?
[308] Fix | Delete
kwds = dict(kwds)
[309] Fix | Delete
if namespace is None:
[310] Fix | Delete
namespace = {}
[311] Fix | Delete
[312] Fix | Delete
self.__dict__ = namespace
[313] Fix | Delete
self.func = func
[314] Fix | Delete
self.args = args
[315] Fix | Delete
self.keywords = kwds
[316] Fix | Delete
[317] Fix | Delete
try:
[318] Fix | Delete
from _functools import partial
[319] Fix | Delete
except ImportError:
[320] Fix | Delete
pass
[321] Fix | Delete
[322] Fix | Delete
# Descriptor version
[323] Fix | Delete
class partialmethod(object):
[324] Fix | Delete
"""Method descriptor with partial application of the given arguments
[325] Fix | Delete
and keywords.
[326] Fix | Delete
[327] Fix | Delete
Supports wrapping existing descriptors and handles non-descriptor
[328] Fix | Delete
callables as instance methods.
[329] Fix | Delete
"""
[330] Fix | Delete
[331] Fix | Delete
def __init__(self, func, *args, **keywords):
[332] Fix | Delete
if not callable(func) and not hasattr(func, "__get__"):
[333] Fix | Delete
raise TypeError("{!r} is not callable or a descriptor"
[334] Fix | Delete
.format(func))
[335] Fix | Delete
[336] Fix | Delete
# func could be a descriptor like classmethod which isn't callable,
[337] Fix | Delete
# so we can't inherit from partial (it verifies func is callable)
[338] Fix | Delete
if isinstance(func, partialmethod):
[339] Fix | Delete
# flattening is mandatory in order to place cls/self before all
[340] Fix | Delete
# other arguments
[341] Fix | Delete
# it's also more efficient since only one function will be called
[342] Fix | Delete
self.func = func.func
[343] Fix | Delete
self.args = func.args + args
[344] Fix | Delete
self.keywords = func.keywords.copy()
[345] Fix | Delete
self.keywords.update(keywords)
[346] Fix | Delete
else:
[347] Fix | Delete
self.func = func
[348] Fix | Delete
self.args = args
[349] Fix | Delete
self.keywords = keywords
[350] Fix | Delete
[351] Fix | Delete
def __repr__(self):
[352] Fix | Delete
args = ", ".join(map(repr, self.args))
[353] Fix | Delete
keywords = ", ".join("{}={!r}".format(k, v)
[354] Fix | Delete
for k, v in self.keywords.items())
[355] Fix | Delete
format_string = "{module}.{cls}({func}, {args}, {keywords})"
[356] Fix | Delete
return format_string.format(module=self.__class__.__module__,
[357] Fix | Delete
cls=self.__class__.__qualname__,
[358] Fix | Delete
func=self.func,
[359] Fix | Delete
args=args,
[360] Fix | Delete
keywords=keywords)
[361] Fix | Delete
[362] Fix | Delete
def _make_unbound_method(self):
[363] Fix | Delete
def _method(*args, **keywords):
[364] Fix | Delete
call_keywords = self.keywords.copy()
[365] Fix | Delete
call_keywords.update(keywords)
[366] Fix | Delete
cls_or_self, *rest = args
[367] Fix | Delete
call_args = (cls_or_self,) + self.args + tuple(rest)
[368] Fix | Delete
return self.func(*call_args, **call_keywords)
[369] Fix | Delete
_method.__isabstractmethod__ = self.__isabstractmethod__
[370] Fix | Delete
_method._partialmethod = self
[371] Fix | Delete
return _method
[372] Fix | Delete
[373] Fix | Delete
def __get__(self, obj, cls):
[374] Fix | Delete
get = getattr(self.func, "__get__", None)
[375] Fix | Delete
result = None
[376] Fix | Delete
if get is not None:
[377] Fix | Delete
new_func = get(obj, cls)
[378] Fix | Delete
if new_func is not self.func:
[379] Fix | Delete
# Assume __get__ returning something new indicates the
[380] Fix | Delete
# creation of an appropriate callable
[381] Fix | Delete
result = partial(new_func, *self.args, **self.keywords)
[382] Fix | Delete
try:
[383] Fix | Delete
result.__self__ = new_func.__self__
[384] Fix | Delete
except AttributeError:
[385] Fix | Delete
pass
[386] Fix | Delete
if result is None:
[387] Fix | Delete
# If the underlying descriptor didn't do anything, treat this
[388] Fix | Delete
# like an instance method
[389] Fix | Delete
result = self._make_unbound_method().__get__(obj, cls)
[390] Fix | Delete
return result
[391] Fix | Delete
[392] Fix | Delete
@property
[393] Fix | Delete
def __isabstractmethod__(self):
[394] Fix | Delete
return getattr(self.func, "__isabstractmethod__", False)
[395] Fix | Delete
[396] Fix | Delete
[397] Fix | Delete
################################################################################
[398] Fix | Delete
### LRU Cache function decorator
[399] Fix | Delete
################################################################################
[400] Fix | Delete
[401] Fix | Delete
_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
[402] Fix | Delete
[403] Fix | Delete
class _HashedSeq(list):
[404] Fix | Delete
""" This class guarantees that hash() will be called no more than once
[405] Fix | Delete
per element. This is important because the lru_cache() will hash
[406] Fix | Delete
the key multiple times on a cache miss.
[407] Fix | Delete
[408] Fix | Delete
"""
[409] Fix | Delete
[410] Fix | Delete
__slots__ = 'hashvalue'
[411] Fix | Delete
[412] Fix | Delete
def __init__(self, tup, hash=hash):
[413] Fix | Delete
self[:] = tup
[414] Fix | Delete
self.hashvalue = hash(tup)
[415] Fix | Delete
[416] Fix | Delete
def __hash__(self):
[417] Fix | Delete
return self.hashvalue
[418] Fix | Delete
[419] Fix | Delete
def _make_key(args, kwds, typed,
[420] Fix | Delete
kwd_mark = (object(),),
[421] Fix | Delete
fasttypes = {int, str, frozenset, type(None)},
[422] Fix | Delete
tuple=tuple, type=type, len=len):
[423] Fix | Delete
"""Make a cache key from optionally typed positional and keyword arguments
[424] Fix | Delete
[425] Fix | Delete
The key is constructed in a way that is flat as possible rather than
[426] Fix | Delete
as a nested structure that would take more memory.
[427] Fix | Delete
[428] Fix | Delete
If there is only a single argument and its data type is known to cache
[429] Fix | Delete
its hash value, then that argument is returned without a wrapper. This
[430] Fix | Delete
saves space and improves lookup speed.
[431] Fix | Delete
[432] Fix | Delete
"""
[433] Fix | Delete
key = args
[434] Fix | Delete
if kwds:
[435] Fix | Delete
key += kwd_mark
[436] Fix | Delete
for item in kwds.items():
[437] Fix | Delete
key += item
[438] Fix | Delete
if typed:
[439] Fix | Delete
key += tuple(type(v) for v in args)
[440] Fix | Delete
if kwds:
[441] Fix | Delete
key += tuple(type(v) for v in kwds.values())
[442] Fix | Delete
elif len(key) == 1 and type(key[0]) in fasttypes:
[443] Fix | Delete
return key[0]
[444] Fix | Delete
return _HashedSeq(key)
[445] Fix | Delete
[446] Fix | Delete
def lru_cache(maxsize=128, typed=False):
[447] Fix | Delete
"""Least-recently-used cache decorator.
[448] Fix | Delete
[449] Fix | Delete
If *maxsize* is set to None, the LRU features are disabled and the cache
[450] Fix | Delete
can grow without bound.
[451] Fix | Delete
[452] Fix | Delete
If *typed* is True, arguments of different types will be cached separately.
[453] Fix | Delete
For example, f(3.0) and f(3) will be treated as distinct calls with
[454] Fix | Delete
distinct results.
[455] Fix | Delete
[456] Fix | Delete
Arguments to the cached function must be hashable.
[457] Fix | Delete
[458] Fix | Delete
View the cache statistics named tuple (hits, misses, maxsize, currsize)
[459] Fix | Delete
with f.cache_info(). Clear the cache and statistics with f.cache_clear().
[460] Fix | Delete
Access the underlying function with f.__wrapped__.
[461] Fix | Delete
[462] Fix | Delete
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
[463] Fix | Delete
[464] Fix | Delete
"""
[465] Fix | Delete
[466] Fix | Delete
# Users should only access the lru_cache through its public API:
[467] Fix | Delete
# cache_info, cache_clear, and f.__wrapped__
[468] Fix | Delete
# The internals of the lru_cache are encapsulated for thread safety and
[469] Fix | Delete
# to allow the implementation to change (including a possible C version).
[470] Fix | Delete
[471] Fix | Delete
# Early detection of an erroneous call to @lru_cache without any arguments
[472] Fix | Delete
# resulting in the inner function being passed to maxsize instead of an
[473] Fix | Delete
# integer or None.
[474] Fix | Delete
if maxsize is not None and not isinstance(maxsize, int):
[475] Fix | Delete
raise TypeError('Expected maxsize to be an integer or None')
[476] Fix | Delete
[477] Fix | Delete
def decorating_function(user_function):
[478] Fix | Delete
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
[479] Fix | Delete
return update_wrapper(wrapper, user_function)
[480] Fix | Delete
[481] Fix | Delete
return decorating_function
[482] Fix | Delete
[483] Fix | Delete
def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):
[484] Fix | Delete
# Constants shared by all lru cache instances:
[485] Fix | Delete
sentinel = object() # unique object used to signal cache misses
[486] Fix | Delete
make_key = _make_key # build a key from the function arguments
[487] Fix | Delete
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
[488] Fix | Delete
[489] Fix | Delete
cache = {}
[490] Fix | Delete
hits = misses = 0
[491] Fix | Delete
full = False
[492] Fix | Delete
cache_get = cache.get # bound method to lookup a key or return None
[493] Fix | Delete
cache_len = cache.__len__ # get cache size without calling len()
[494] Fix | Delete
lock = RLock() # because linkedlist updates aren't threadsafe
[495] Fix | Delete
root = [] # root of the circular doubly linked list
[496] Fix | Delete
root[:] = [root, root, None, None] # initialize by pointing to self
[497] Fix | Delete
[498] Fix | Delete
if maxsize == 0:
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function