如何在我的包中使用装饰器

How to use decorator in my package

我想在我的原始包中使用原始装饰器(例如 'mypackage' 中的'with_error_handler')并执行一些功能。 但它 returns 函数对象或错误信息太给定参数了。

在我的包裹中:

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>

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

没有必要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,){})