@functools.lru_cache(maxsize=128, typed=False)
maxsize最好是a power-of-two,如果缓存数据超出maxsize的值,就是用LRU(最近最少使用算法)清除一些缓存结果。
import urllib.error
import urllib.request
from functools import lru_cache
@lru_cache(maxsize=32)
def get_pep(num):
resource = 'http://www.python.org/dev/peps/pep-%04d/'% num
try:
with urllib.request.urlopen(resource) as s:
return s.read()
except urllib.error.HTTPError:
return 'Not Found'
if __name__ == '__main__':
for n in 8,290,308,320,8,218,320,279,289,320,9991:
pep = get_pep(n)
print(n,len(pep))
print(get_pep.cache_info())
>>>
8 116713
290 64288
308 51317
320 51820
8 116713
218 47839
320 51820
279 49780
289 51829
320 51820
9991 9
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
总共有11个访问请求,8有两个,320有3个。第一次访问时候请求服务器,第二次就从缓存中取
functools.partial(func, *args, **keywords)
与下面的函数实现相当
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
from functools import partial
p_add = partial(add,2)
print(p_add)
print(p_add(4))
>>>
functools.partial(<function add at 0x0000000002A75620>, 2)
6
#coding:UTF-8
from functools import partial
def add(x,y):
return x+y
def multiply(x,y):
return x*y
def run(func):
print(func())
if __name__ == '__main__':
a1 = partial(add,1,2)
m1 = partial(multiply,5,8)
run(a1)
run(m1)
@functools.singledispatch(default)
from functools import singledispatch
@singledispatch
def add(a,b):
raise NotImplementedError('Unsupported type')
@add.register(int)
def _(a,b):
print('First argument is of type',type(a))
print(a+b)
@add.register(str)
def _(a,b):
print('First argument is of type',type(a))
print(a+b)
@add.register(list)
def _(a,b):
print('First argument is of type',type(a))
print(a+b)
if __name__ == '__main__':
add(1,2)
add('Python','Programming')
add([1,2,3],[5,6,7])
print(add.registry.keys())
>>>
First argument is of type <class 'int'>
3
First argument is of type <class 'str'>
PythonProgramming
First argument is of type <class 'list'>
[1, 2, 3, 5, 6, 7]
dict_keys([<class 'object'>, <class 'int'>, <class 'str'>, <class 'list'>])