如何在我的包中使用decorator

2024-09-25 08:25:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的原始包中使用原始decorator(例如“mypackage”中的“with\u error\u handler”)并执行一些函数。 但它返回的函数对象或错误消息太给定的参数。你知道吗

在我的包中:

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>

为什么会发生这些错误? 如何修复?你知道吗


Tags: 函数importdef错误withargsdecoratorerror
1条回答
网友
1楼 · 发布于 2024-09-25 08:25:27

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

相关问题 更多 >