functools

2690 ワード

@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(, 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 
3
First argument is of type 
PythonProgramming
First argument is of type 
[1, 2, 3, 5, 6, 7]
dict_keys([, , , ])