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