python使用装饰器捕获异常

可以编写一个通用的捕获异常的装饰器, 当程序发生异常时可以继续执行后续动作。 尤其适合于使用大量断言的验证性程序。

装饰器的实现原理使用了回调技术。

如下所示, robust 是一个装饰器。 当在普通函数 func 加上 @robust 注解时, 即是给 func 加上了 robust 装饰。 当调用 func 时, 就会实际地执行 robust , 获取装饰后的函数 add_robust , 调用 add_robust 来完成实际的动作。  即调用:     func(*arg, **keyargs)  等效于  robust(simple)(*arg, **keyargs)

#-------------------------------------------------------------------------------
# Name:        deco.py
# Purpose:     demo of decoration in python
#
# Author:      qin.shuq
#
# Created:     27/10/2014
#-------------------------------------------------------------------------------

import traceback

def robust(actual_do):
    def add_robust(*args, **keyargs):
        try:
            return actual_do(*args, **keyargs)
        except:
            print ‘Error execute: %s‘ % actual_do.__name__
            #traceback.print_exc()
    return add_robust

@robust
def simple():
    return 5 / 0

@robust
def readFile(filename):
    f = open(filename, "r")
    print len(f.readlines())
    f.close()

def add(a,b):
    return int(a)+int(b)

@robust
def assertSumIsPositive(*args):
    sum = reduce(add, *args)
    assert sum >= 0

@robust
def checkLen(**keyargs):
    if len(keyargs) < 3:
        raise Exception(‘Number of key args should more than 3.‘)

if __name__ == ‘__main__‘:
    simple()
    readFile("UnexistFile.txt")
    assertSumIsPositive(1,2,-3,-4)
    checkLen(a=5,b=2)
    print ‘Yet still reach here.‘
时间: 2024-08-26 12:00:41

python使用装饰器捕获异常的相关文章

尝试自己的Perl语言的包 TCP协议的再包装起到类似python语言装饰器的效果

#!/usr/bin/perl # Filename: BuildSocketTCP.pm # #   Copyright 2012 Axxeo GmbH #   Licensed under the Apache License, Version 2.0 (the "License"); #   you may not use this file except in compliance with the License. #   You may obtain a copy of t

尝试自己的Perl语言的包 UDP协议的再包装起到类似python语言装饰器的效果

#!/usr/bin/perl # Filename: BuildSocketUDP.pm # #   Copyright 2012 Axxeo GmbH #   Licensed under the Apache License, Version 2.0 (the "License"); #   you may not use this file except in compliance with the License. #   You may obtain a copy of t

python函数装饰器

学习装饰器前提需要了解高阶函数,函数嵌套,函数闭包 python函数装饰器,顾名思义就是装饰函数,为函数添加新功能的的一种方式. 为什么要使用装饰器呢? 因为函数在运行时,如果不使用装饰器对函数进行功能添加,需要修改函数源代码,这样修改无疑会增加程序的冗余和复杂性,也不便于程序员对其进行修改.使用装饰器,可以在不改变函数源代码和调用方式的前提下,使用语法糖@装饰器,对函数功能进行添加. 装饰器本质上就是一个函数. 我们使用一个简单的例子来实现: import time #这是一个装饰器函数名为t

Python之装饰器、迭代器和生成器

在学习python的时候,三大“名器”对没有其他语言编程经验的人来说,应该算是一个小难点,本次博客就博主自己对装饰器.迭代器和生成器理解进行解释. 为什么要使用装饰器 什么是装饰器?“装饰”从字面意思来谁就是对特定的建筑物内按照一定的思路和风格进行美化的一种行为,所谓“器”就是工具,对于python来说装饰器就是能够在不修改原始的代码情况下给其添加新的功能,比如一款软件上线之后,我们需要在不修改源代码和不修改被调用的方式的情况下还能为期添加新的功能,在python种就可以用装饰器来实现,同样在写

python之装饰器 实例

=====================================写法1========================== import time def timer(func):     def deco():         start_time = time.time()         func()         stop_time = time.time()         print('the func run time is %s' %(stop_time - star

【转】详解Python的装饰器

原文链接:http://python.jobbole.com/86717/ Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现了say_hello()和say_goodbye()两个函数. def say_hello(): print "hello!" def say_goodbye(): print "hello!" # bug here if __name__ == '__main__':

如何用python的装饰器定义一个像C++一样的强类型函数

Python作为一个动态的脚本语言,其函数在定义时是不需要指出参数的类型,也不需要指出函数是否有返回值.本文将介绍如何使用python的装饰器来定义一个像C++那样的强类型函数.接下去,先介绍python3中关于函数的定义. 0. python3中的函数定义 举个例子来说吧,比如如下的函数定义: 1 def fun(a:int, b=1, *c, d, e=2, **f) -> str: 2 pass 这里主要是说几点与python2中不同的点. 1)分号后面表示参数的annotation,这个

Python 函数装饰器入门

原文链接: --> A guide to Python's function decorators Python功能强劲,语法表现力强,尤其装饰器深深的吸引着我.在设计模式中,装饰器可以在不使用子类的情况下,动态的改变函数,方法以及类的功能.这个功能非常有用,特别在你想扩展函数的功能同时又不想改变原有的函数.的确,我们任意的实现装饰器设计模式,但是,python通过提供简单的语法和特性让装饰器的实现变的如此简单. 在本文中,我将用一组例子来深入浅入python 函数装饰器的功能,所有的例子都是在

关于Python的装饰器(1)

Python的装饰器的概念,一直有点微妙.之前在StackOverflow上看过一篇感觉说明的很清楚的介绍: *A decorator must accept a function as an argument 参考地址: http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/1594484#1594484 http://stackoverflow.com