对于Python装饰器使用的一些建议


Posted in Python onJune 03, 2015

装饰器基本概念

大家都知道装饰器是一个很著名的设计模式,经常被用于 AOP (面向切面编程)的场景,较为经典的有插入日志,性能测试,事务处理,Web权限校验, Cache等。

Python 语言本身提供了装饰器语法(@),典型的装饰器实现如下:

@function_wrapper
  def function():
    pass

@实际上是 python2.4 才提出的语法糖,针对 python2.4 以前的版本有另一种等价的实现:

def function():
    pass

  function = function_wrapper(function)

装饰器的两种实现

函数包装器 - 经典实现

def function_wrapper(wrapped):
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)
    return _wrapper 

  @function_wrapper
  def function():
    pass

类包装器 - 易于理解

class function_wrapper(object):
    def __init__(self, wrapped):
      self.wrapped = wrapped
    def __call__(self, *args, **kwargs):
      return self.wrapped(*args, **kwargs)

  @function_wrapper
  def function():
    pass

函数(function)自省

当我们谈到一个函数时,通常希望这个函数的属性像其文档上描述的那样,是被明确定义的,例如__name__ 和__doc__ 。

针对某个函数应用装饰器时,这个函数的属性就会发生变化,但这并不是我们所期望的。

def function_wrapper(wrapped):
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)
    return _wrapper 

  @function_wrapper
  def function():
    pass 

  >>> print(function.__name__)
  _wrapper

python 标准库提供了functools.wraps(),来解决这个问题。

import functools 

  def function_wrapper(wrapped):
    @functools.wraps(wrapped)
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)
    return _wrapper 

  @function_wrapper
  def function():
    pass 

  >>> print(function.__name__)
  function

然而,当我们想要获取被包装函数的参数(argument)或源代码(source code)时,同样不能得到我们想要的结果。

import inspect 

  def function_wrapper(wrapped): ...

  @function_wrapper
  def function(arg1, arg2): pass 

  >>> print(inspect.getargspec(function))
  ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)

  >>> print(inspect.getsource(function))
    @functools.wraps(wrapped)
    def _wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)

包装类方法(@classmethod)

当包装器(@function_wrapper)被应用于@classmethod时,将会抛出如下异常:

class Class(object):
    @function_wrapper
    @classmethod
    def cmethod(cls):
      pass 

  Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 3, in Class
   File "<stdin>", line 2, in wrapper
   File ".../functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
  AttributeError: 'classmethod' object has no attribute '__module__'

因为@classmethod在实现时,缺少functools.update_wrapper需要的某些属性。这是functools.update_wrapper在 python2 中的 bug,3.2版本已被修复,参考 http://bugs.python.org/issue3445。

然而,在 python3 下执行,另一个问题出现了:

class Class(object):
    @function_wrapper
    @classmethod
    def cmethod(cls):
      pass 

  >>> Class.cmethod() 
  Traceback (most recent call last):
   File "classmethod.py", line 15, in <module>
    Class.cmethod()
   File "classmethod.py", line 6, in _wrapper
    return wrapped(*args, **kwargs)
  TypeError: 'classmethod' object is not callable

这是因为包装器认定被包装的函数(@classmethod )是可以直接被调用的,但事实并不一定是这样的。被包装的函数实际上可能是描述符(descriptor ),意味着为了使其可调用,该函数(描述符)必须被正确地绑定到某个实例上。关于描述符的定义,可以参考 https://docs.python.org/2/howto/descriptor.html。
总结 - 简单并不意味着正确

尽管大家实现装饰器所用的方法通常都很简单,但这并不意味着它们一定是正确的并且始终能正常工作。

如同上面我们所看到的,functools.wraps() 可以帮我们解决__name__ 和__doc__ 的问题,但对于获取函数的参数(argument)或源代码( source code )则束手无策。

Python 相关文章推荐
Python实现子类调用父类的方法
Nov 10 Python
python实现将汉字转换成汉语拼音的库
May 05 Python
Python中线程编程之threading模块的使用详解
Jun 23 Python
Python卸载模块的方法汇总
Jun 07 Python
Python使用dis模块把Python反编译为字节码的用法详解
Jun 14 Python
详解python3百度指数抓取实例
Dec 12 Python
python使用PyCharm进行远程开发和调试
Nov 02 Python
Python语言的变量认识及操作方法
Feb 11 Python
利用Python代码实现数据可视化的5种方法详解
Mar 25 Python
Django中celery执行任务结果的保存方法
Jul 12 Python
python基于TCP实现的文件下载器功能案例
Dec 10 Python
解决hive中导入text文件遇到的坑
Apr 07 Python
Python模块搜索概念介绍及模块安装方法介绍
Jun 03 #Python
Python使用ftplib实现简易FTP客户端的方法
Jun 03 #Python
Python中的深拷贝和浅拷贝详解
Jun 03 #Python
python下paramiko模块实现ssh连接登录Linux服务器
Jun 03 #Python
python处理二进制数据的方法
Jun 03 #Python
Python读写配置文件的方法
Jun 03 #Python
python操作ssh实现服务器日志下载的方法
Jun 03 #Python
You might like
基于simple_html_dom的使用小结
2013/07/01 PHP
Yii框架引用插件和ckeditor中body与P标签去除的方法
2017/01/19 PHP
php 使用curl模拟ip和来源进行访问的实现方法
2017/05/02 PHP
php制作圆形用户头像的实例_自定义封装类源代码
2017/09/18 PHP
Alliance vs Liquid BO3 第二场2.13
2021/03/10 DOTA
js加解密 脚本解密
2008/02/22 Javascript
颜色选择器 Color Picker,IE,Firefox,Opera,Safar
2010/11/25 Javascript
与jquery serializeArray()一起使用的函数,主要来方便提交表单
2011/01/31 Javascript
iframe 异步加载技术及性能分析
2011/07/19 Javascript
jQuery实现切换页面布局使用介绍
2011/10/09 Javascript
jQuery源码分析-02正则表达式 RegExp 常用正则表达式
2011/11/14 Javascript
父页面显示遮罩层弹出半透明状态的dialog
2014/03/04 Javascript
jquery css 设置table的奇偶行背景色示例
2014/06/03 Javascript
javascript表格隔行变色加鼠标移入移出及点击效果的方法
2015/04/10 Javascript
移除AngularJS下URL中的#字符的方法
2015/06/19 Javascript
jQuery实现TAB风格的全国省份城市滑动切换效果代码
2015/08/24 Javascript
数据结构中的各种排序方法小结(JS实现)
2016/07/23 Javascript
nodejs的安装使用与npm的介绍
2019/09/11 NodeJs
python转换字符串为摩尔斯电码的方法
2015/07/06 Python
python判断字符串或者集合是否为空的实例
2019/01/23 Python
将python运行结果保存至本地文件中的示例讲解
2019/07/11 Python
elasticsearch python 查询的两种方法
2019/08/04 Python
python 进程间数据共享multiProcess.Manger实现解析
2019/09/23 Python
pygame实现俄罗斯方块游戏(对战篇1)
2019/10/29 Python
Python基础之函数原理与应用实例详解
2020/01/03 Python
ProBikeKit英国:在线公路自行车之家
2017/02/10 全球购物
java程序员面试交流
2012/11/29 面试题
物流仓管员工作职责
2014/01/06 职场文书
《小儿垂钓》教学反思
2014/02/23 职场文书
可口可乐广告词
2014/03/20 职场文书
5s推行计划书
2014/05/06 职场文书
旷工检讨书大全
2015/08/15 职场文书
护士业务学习心得体会
2016/01/25 职场文书
浅谈MySQL user权限表
2021/06/18 MySQL
Python 多线程处理任务实例
2021/11/07 Python
Django中celery的使用项目实例
2022/07/07 Python