自定义函数必需参数的Python错误消息

huangapple go评论104阅读模式
英文:

python custom error message for required parameters of a function

问题

在Python中,对于一个函数,在未传递所需参数时,Python会引发TypeError。如何自定义这个TypeError的错误消息呢?例如:

>>> def f(a):
...     print('a')
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() missing 1 required positional argument: 'a'

我希望自定义错误消息以包含有关错误消息的更多信息,比如参数的定义。这是否可行,或者有没有更好的方法来做同样的事情?

英文:

In python, for a function, when a required parameter is not passed, python raises a TypeError. How can I customize the error message of this TypeError. For example:

&gt;&gt;&gt; def f(a):
...     print(&#39;a&#39;)
...
&gt;&gt;&gt; f()
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
TypeError: f() missing 1 required positional argument: &#39;a&#39;

I wish to customise the error message to include more information about the error message, like the definition of parameter. Is this doable or is their a better way to do the same?

答案1

得分: 1

我认为你不能在Python中更改默认的异常错误,但你可以通过一些技巧来获取自定义消息。

一个想法可以是仅使用try except:

try:
    f()
except TypeError as e:
    raise TypeError("你想要编写的任何消息...")

第二个想法是给你的参数一些默认选项,比如None,并在你的函数中检查它是否为None:

def f(a: Optional[int] = None) -> None:
    if a is None:
        raise TypeError("你想要引发的消息")
    print(a)

最后一个想法是将第一个和第二个想法结合起来使用装饰器。你可以通过装饰器来检查它是否具有你定义的函数所需的适当参数:

import functools

def custom_type_error_for_functions(func):
    functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except TypeError as e:
            raise TypeError("你想要引发的消息")
    return wrapper

将此装饰器放在你的函数之上你就可以使用它了

```python
@custom_type_error_for_functions
def f(a):
    print(a)
英文:

I think you cannot change the default exception errors in python, but you can do some tricks to get your custom message.

one idea can be use just try except:

try:
    f()
except TypeError as e:
    raise TypeError(&quot;Any message you like to write...&quot;)

second idea is to give your parameter some default option like None, and check it in your function whether it is None or not:

def f(a: Optional[int] = None) -&gt; None:
    if a is None:
        raise TypeError(&quot;The message you want to raise&quot;)
    print(a)

and the final idea is combination of first and second idea with the decorators. You can check that by the decorator if it has the appropriate parameters for the function you defined:

import functools

def custom_type_error_for_functions(func):
    functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except TypeError as e:
            raise TypeError(&quot;The message you want to raise&quot;)
    return wrapper

put this decorator on top of your function and you are good to go:

@custom_type_error_for_functions
def f(a):
    print(a)

huangapple
  • 本文由 发表于 2023年8月10日 15:37:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定