如何在我的包

时间:2017-11-22 13:49:53

标签: python python-3.x package decorator wrapper

我想在原始包中使用原始装饰器(例如' with_error_handler'在mypackage'中)并执行一些功能。 但是它返回了给出参数的函数对象或错误按摩。

在我的包裹中:

def with_error_handler(func):
    import traceback
    from functools import wraps
    from decorator import decorator
    @decorator
    @wraps(func)
    def error_handler(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            strError = traceback.format_exc() + __file__ + '(' + str(args) + str(kwargs) + ')'
            print(strError)
    return error_handler

我想执行以下代码。

import mypackage

@mypackage.with_error_handler
def divnum(num):
    print(1/num)

@mypackage.with_error_handler
def divone():
    print(1/1)

if __name__ == '__main__':
    divnum(2)
    divone()

这些结果在这里

>>>divnum(2)
・・・with_error_handler() takes 1 positional argument but 2 were given
>>>divone()
・・・<function __main__.divone>

为什么会出现这些错误? 如何解决?

1 个答案:

答案 0 :(得分:1)

无需from decorator import decorator。做

import functools as ft
import traceback

def with_error_handler(func):
    @ft.wraps(func)
    def error_handler(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            strError = traceback.format_exc() + __file__ + '(' + str(args) + str(kwargs) + ')'
            print(strError)
    return error_handler

没关系。

>>> divone()
1.0
>>> divnum(2)
0.5

并按预期

>>> divnum(0)
Traceback (most recent call last): 
  File "/home/user/mypackage.py", line <X>, in error_handler
    return func(*args, **kwargs)
  File "/home/user/mypackagetest.py", line <Y>, in divnum
    print(1/num)
ZeroDivisionError: division by zero 
/home/user/mypackage.py((0,){})