项目中遇到的装饰器

1. functools.partial

django 用法:python

  • 代码出现的地方django

    path = partial(_path, Pattern=RoutePattern)
    re_path = partial(_path, Pattern=RegexPattern)
  • 详解缓存

    # 调用path时至关于调用_path('login/', LoginView.as_view(), Pattern=RoutePattern)
    urlpatterns = [
        path('login/', LoginView.as_view()),
    ]

2. functools.lru_cache

django:app

  • manage.py 命令行执行时fetch_command函数调用get_commands函数

  • get_commands每次调用都会返回一个dict,当settings文件没有改变的时,返回的值是不变的,使用装饰器则减小了每次启动服务计算commands的时间fetch

    @functools.lru_cache(maxsize=None)
    def get_commands():
        commands = {name: 'django.core' for name in find_commands(__path__[0])}
    
        if not settings.configured:
            return commands
    
        for app_config in reversed(list(apps.get_app_configs())):
            path = os.path.join(app_config.path, 'management')
            commands.update({name: app_config.name for name in find_commands(path)})
    
        return commands
  • functools.lru_cache(maxsize=128, typed=False)this

    -- maxsize表明缓存的内存占用值,超过这个值以后,以前的结果就会被释放,而后将新的计算结果进行缓存,其值应当设为2的幂
    -- typed若为True,则会把不一样的参数类型获得的结果分开保存
  • 做用:主要是用来作临时缓存,把耗时的操做结果暂时保存,避免重复计算,好比生成斐波那契数列时,函数后觉得结果依赖前两位计算结果值url

3. classonlymethod 和 classmethod

  • django CBV 中 类继承View类,urlpattern里面调用as_view实现一个接口不一样不一样调用方式走不一样的逻辑,as_view方法使用@classonlymethod装饰器
  • 源码
    class classonlymethod(classmethod):
         def __get__(self, instance, cls=None):
             if instance is not None:
                 raise AttributeError("This method is available only on the class, not on instances.")
             return super().__get__(instance, cls)
  • 源码能够看出classonlymethod和classmethod的区别即为,classonlymethod只能由类调用,实例对象调用时会抛出对象异常

4. @functools.wraps(func) 用于定义装饰器的时候,特别是多个函数被装饰器装饰时,保留原函数的名称和属性

  • 使用示例:
    def my_decorator(func):      
         @functools.wraps(func)
         def wrapper(*args, **kwargs):
             '''do something'''
             return func(*args, **kwargs)
         return wrapper
  • 源码,根据源码能够看出wraps 函数实现了更新包装器函数,将被包装的函数属性赋给新的包装器函数并返回,因此说该函数的做用是保留被装饰对象的属性
    # 使用偏函数,对传进来的包装器函数调用update_wrapper
     # 返回一个装饰器,该装饰器使用装饰后的函数做为包装器参数并调用wraps()的参数做为其他参数来调用update_wrapper()。 
     # 默认参数与update_wrapper()相同。
     def wraps(wrapped,
               assigned = WRAPPER_ASSIGNMENTS,
               updated = WRAPPER_UPDATES):
         """Decorator factory to apply update_wrapper() to a wrapper function
            Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the remaining arguments. Default arguments are as for update_wrapper().
            This is a convenience function to simplify applying partial() to update_wrapper().
         """
         return partial(update_wrapper, wrapped=wrapped,
                        assigned=assigned, updated=updated)
     def update_wrapper(wrapper,
                        wrapped,
                        assigned = WRAPPER_ASSIGNMENTS,
                        updated = WRAPPER_UPDATES):
         """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) updated is a tuple naming the attributes of the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES)
         """
         for attr in assigned:
             try:
                 value = getattr(wrapped, attr)
             except AttributeError:
                 pass
             else:
                 setattr(wrapper, attr, value)
         for attr in updated:
             getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
         # Issue #17482: set __wrapped__ last so we don't inadvertently copy it      
         # from the wrapped function when updating __dict__
         wrapper.__wrapped__ = wrapped
         # Return the wrapper so this can be used as a decorator via partial()
         return wrapper
相关文章
相关标签/搜索