python 牛逼的functools.py
2021-04-25 07:29
                         标签:try   code   写法   def   function   ESS   pass   wrap   cep    https://zhuanlan.zhihu.com/p/26546486 python 牛逼的functools.py 标签:try   code   写法   def   function   ESS   pass   wrap   cep    原文地址:https://www.cnblogs.com/amize/p/13258849.html
functools.wraps
# Flask CBV 写法
import functools
from flask import Flask, views
app = Flask(__name__)
def wrapper(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)
    return inner
class UserView(views.MethodView):
    methods = [‘GET‘]
    decorators = [wrapper, ]
    def get(self, *args, **kwargs):
        return ‘GET‘
    def post(self, *args, **kwargs):
        return ‘POST‘
app.add_url_rule(‘/user‘, None, UserView.as_view(‘uuuu‘))
if __name__ == ‘__main__‘:
    app.run()
functools.partial
#Flask中应用
request = functools.partial(_lookup_req_object,‘request‘)
session = functools.partial(_lookup_req_object,‘session‘)
functools.cmp_to_key
#unittest中应用
‘‘‘
loader.py
‘‘‘
sortTestMethodsUsing = staticmethod(util.three_way_cmp)
if self.sortTestMethodsUsing:
    testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
‘‘‘
util.py
‘‘‘
def three_way_cmp(x, y):
    """Return -1 if x  y"""
    return (x > y) - (x  0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) = 0
        __hash__ = None
    return K
try:
    from _functools import cmp_to_key
except ImportError:
    pass
待加入