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()
8 9
290 9
308 9
320 9
8 9
218 9
320 9
279 9
289 9
320 9
9991 9
Out[4]:
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
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]:
18
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]:
True
In [7]:
functools.reduce(lambda x, y: x+[y], range(10), [])
Out[7]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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())
print A obj:  <__main__.A object at 0x10c944978>
print B obj:  <__main__.B object at 0x10c9449e8>
print C obj:  <__main__.C object at 0x10c944978>
print B obj:  <__main__.D object at 0x10c9449e8>
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))
Calling decorated function
Called example function
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__wrapped__']
functools.partial(<function update_wrapper at 0x10aa9d8c8>, wrapped=<class 'int'>, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))
In [9]:
 
In [9]:
 
Comments powered by Disqus