1.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 >>> basetwo = partial(int, base=2) >>> basetwo.__doc__ = ‘Convert base 2 string to an int.‘ >>> basetwo(‘10010‘) 18
2.functools.
update_wrapper
(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
将wrapper function更新为wrapped function,多用于decorator,以decorator module中提到的一个例子(用于实现缓存)
def memoize_uw(func): func.cache = {} def memoize(*args, **kw): if kw: # frozenset is used to ensure hashability key = args, frozenset(kw.items()) else: key = args if key not in func.cache: func.cache[key] = func(*args, **kw) return func.cache[key] return functools.update_wrapper(memoize, func)
这里memoize就是wrapper function,func就是wrapped function,使用update_wrapper“更新"的内容包括__name__, __doc__, __module__, __dict__,
不更新的情况下以上四项与memoize保持一致。
[email protected]
functools.
wraps
(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
wraps是update_wrapper的语法糖,从parameter来看就知道少了一个wrapper,于是乎就可以写成
@wraps(func)
def memoize(*args, **kw)
时间: 2024-12-30 11:19:43