英文:
python custom error message for required parameters of a function
问题 {#heading}
在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:
>>> 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'
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}
得分: 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("Any message you like to write...")
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) -> None:
if a is None:
raise TypeError("The message you want to raise")
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("The message you want to raise")
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)