python function tools
In [3]:
import functools
In [4]:
import urllib
@functools.lru_cache(maxsize=32)
def get_pep(num):
'Retrieve text of a Python Enhancement Proposal'
resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
try:
with urllib.request.urlopen(resource) as s:
return s.read()
except:
return 'Not Found'
for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
pep = get_pep(n)
print(n, len(pep))
get_pep.cache_info()
Out[4]:
In [5]:
# functools.partial固定函数可选参数,返回一个函数对象
basetwo = functools.partial(int, base=2)
basetwo.__doc__ = 'Convert base 2 string to an int.'
assert(basetwo('10010') == int('10010', base=2))
basetwo('10010')
Out[5]:
In [6]:
# functools.partialmethod 固定对象成员函数
class Cell(object):
def __init__(self):
self._alive = False
@property
def alive(self):
return self._alive
def set_state(self, state):
self._alive = bool(state)
set_alive = functools.partialmethod(set_state, True)
set_dead = functools.partialmethod(set_state, False)
c = Cell()
c.alive
c.set_alive()
c.alive
Out[6]:
In [7]:
functools.reduce(lambda x, y: x+[y], range(10), [])
Out[7]:
In [8]:
# 函数分发封装
@functools.singledispatch
def fun(arg, verbose=False):
if verbose:
print("Let me just say,", end=" ")
print(arg)
class A(object):
name = "A"
class B(A):
name = "B"
class C(B):
name = "C"
class D(B):
name = "C"
@fun.register(A)
def _(obj):
print("print A obj: ", obj)
@fun.register(B)
def _(obj):
print("print B obj: ", obj)
@fun.register(C)
def _(obj):
print("print C obj: ", obj)
fun(A())
fun(B())
fun(C())
fun(D())
In [9]:
# functools.wraps 函数包装(等同partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated))
def my_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
print('Calling decorated function')
return f(*args, **kwds)
return wrapper
@my_decorator
def example():
"""Docstring"""
print('Called example function')
example()
print(dir(example))
print(functools.wraps(int))
In [9]:
In [9]: