9.8. functools — 可调用对象的高阶函数和操作

2.5 版新增。

源代码: Lib/functools.py


The functools 模块用于高阶函数:充当 (或返回) 其它函数的函数。一般而言,任何可调用对象都可以视为用于此模块用途的函数。

The functools 模块定义了下列函数:

functools. cmp_to_key ( func )

Transform an old-style comparison function to a 关键函数 . Used with tools that accept key functions (such as sorted() , min() , max() , heapq.nlargest() , heapq.nsmallest() , itertools.groupby() ). This function is primarily used as a transition tool for programs being converted to Python 3 where comparison functions are no longer supported.

A comparison function is any callable that accept two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than. A key function is a callable that accepts one argument and returns another value to be used as the sort key.

范例:

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
						

对于排序范例和简短排序教程,见 排序怎么样 .

2.7 版新增。

functools. total_ordering ( cls )

给定定义一个或多个丰富比较次序方法的类,此类装饰器供给其余方法。这简化指定所有可能丰富比较操作涉及的努力:

类必须定义一个 __lt__() , __le__() , __gt__() ,或 __ge__() 。此外,类应提供 __eq__() 方法。

例如:

@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
						

2.7 版新增。

functools. reduce ( function , iterable [ , initializer ] )

This is the same function as reduce() . It is made available in this module to allow writing code more forward-compatible with Python 3.

2.6 版新增。

functools. partial ( func[,*args][, **keywords] )

返回新的 partial object which when called will behave like func called with the positional arguments args 和关键词自变量 keywords . If more arguments are supplied to the call, they are appended to args . If additional keyword arguments are supplied, they extend and override keywords . Roughly equivalent to:

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
						

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
						
functools. update_wrapper ( wrapper, wrapped[, assigned][, updated] )

Update a wrapper function to look like the wrapped function. The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants WRAPPER_ASSIGNMENTS (which assigns to the wrapper function’s __name__ , __module__ and __doc__ , the documentation string) and WRAPPER_UPDATES (which updates the wrapper function’s __dict__ , i.e. the instance dictionary).

The main intended use for this function is in 装饰器 functions which wrap the decorated function and return the wrapper. If the wrapper function is not updated, the metadata of the returned function will reflect the wrapper definition rather than the original function definition, which is typically less than helpful.

functools. wraps ( wrapped[, assigned][, updated] )

这是方便函数为援引 update_wrapper() 作为函数装饰器当定义包裹器函数时。它相当于 partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated) 。例如:

>>> from functools import wraps
>>> def my_decorator(f):
...     @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()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
						

不使用此装饰器工厂,example 函数名称将拥有 'wrapper' ,且 docstring (文档字符串) 对于原始 example() 会丢失。

9.8.1. partial 对象

partial 对象是可调用对象创建通过 partial() 。它们有 3 个只读属性:

partial. func

可调用对象或函数。调用 partial 对象会转发给 func 采用新自变量和关键词。

partial. args

The leftmost positional arguments that will be prepended to the positional arguments provided to a partial object call.

partial. keywords

The keyword arguments that will be supplied when the partial object is called.

partial 对象像 function objects in that they are callable, weak referencable, and can have attributes. There are some important differences. For instance, the __name__ and __doc__ attributes are not created automatically. Also, partial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.