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