Wednesday, October 6, 2010

functools

functools 是为了方便的产生 functors 而设计的库,特别的 functoorls 提供了 decorator 以及 bind 这些常用的 functor。

functools 提供了下面几个工具:
  • cmp_to_key 新的排序等功能都是依照 key 来做的,而不是通过原来那种比较函数(输入两个对象,返回正负零表示大小关系);这个可以将 cmp 类型的函数转换成为 key 类型的;
    total_ordering 是一个 annotation,如果定义了某个类的 __eq__ 和几种比较运算的一种,就可以获得其他所有的类型了;
  • reduce 与 __builtins__.reduce 一样;
  • partial 用于产生 bind 类型的 functor,用法是 partial( func, *args, **dict),例子如 a = partial(int, base=2) 之后 a('01010101') 就跟调用 int( '01010101', base=2) 一样了;
  • wraps 和 update_wrapper 用于产生 wrapper,下面是一个例子。

#!/usr/bin/python

import functools

def normal_func( a, b ):
    print a + ' says: this is a normal function ' + b

def decorator(f):
    @functools.wraps(f)
    def wrapper( *args, **dict ):
        print 'this is the descorator'
        return f( *args, **dict )
    return wrapper

if __name__ == '__main__':
    normal_func( 'foo', 'bar' )
    decorated_func = decorator( normal_func )
    decorated_func( 'tom', 'jerry' )
比较有意思的是这种做法其实可以以工厂方式生产 wrapper。结果如下:
$ ./test10.py 
foo says: this is a normal function bar
this is the descorator
tom says: this is a normal function jerry

No comments:

Post a Comment