cdl*_*ary 496 python arguments exception
我想知道在Python中指示无效参数组合的最佳实践.我遇到过一些你有这样功能的情况:
def import_to_orm(name, save=False, recurse=False):
"""
:param name: Name of some external entity to import.
:param save: Save the ORM object before returning.
:param recurse: Attempt to import associated objects as well. Because you
need the original object to have a key to relate to, save must be
`True` for recurse to be `True`.
:raise BadValueError: If `recurse and not save`.
:return: The ORM object.
"""
pass
Run Code Online (Sandbox Code Playgroud)
唯一令人烦恼的是,每个包装都有自己的,通常略有不同BadValueError.我知道在Java中存在java.lang.IllegalArgumentException- 是否很好理解每个人都将BadValueError在Python中创建自己的s或者是否有另一种首选方法?
dbr*_*dbr 548
我只会提出ValueError,除非你需要一个更具体的例外.
def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")
Run Code Online (Sandbox Code Playgroud)
真的没有意义class BadValueError(ValueError):pass- 您的自定义类与ValueError的使用完全相同,那么为什么不使用它呢?
Mar*_*rot 96
我会继承 ValueError
class IllegalArgumentError(ValueError):
pass
Run Code Online (Sandbox Code Playgroud)
有时候创建自己的异常更好,但是从内置的异常继承,尽可能接近你想要的.
如果您需要捕获该特定错误,那么拥有一个名称会很有帮助.
Glo*_*eye 25
这取决于参数的问题是什么。
如果参数的类型错误,则引发 TypeError。例如,当您获得一个字符串而不是那些布尔值之一时。
if not isinstance(save, bool):
raise TypeError(f"Argument save must be of type bool, not {type(save)}")
Run Code Online (Sandbox Code Playgroud)
但是请注意,在 Python 中我们很少进行这样的检查。如果参数确实无效,一些更深层次的函数可能会为我们抱怨。如果我们只检查布尔值,也许某些代码用户稍后会向它提供一个字符串,因为知道非空字符串始终为 True。这可能会为他节省一个演员。
如果参数具有无效值,则引发 ValueError。这似乎更适合您的情况:
if recurse and not save:
raise ValueError("If recurse is True, save should be True too")
Run Code Online (Sandbox Code Playgroud)
或者在这种特定情况下,递归的真值意味着保存的真值。由于我认为这是从错误中恢复,您可能还想在日志中抱怨。
if recurse and not save:
logging.warning("Bad arguments in import_to_orm() - if recurse is True, so should save be")
save = True
Run Code Online (Sandbox Code Playgroud)
J B*_*nes 12
我认为处理这个的最好方法是python本身处理它的方式.Python引发了一个TypeError.例如:
$ python -c 'print(sum())'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0
Run Code Online (Sandbox Code Playgroud)
我们的初级开发人员刚刚在google搜索"python exception错误论点"中找到了这个页面,我很惊讶,自从提出这个问题以来,十年内没有人提出明显(对我而言)的答案.
小智 9
在这种情况下,您很可能会使用ValueError(raise ValueError()完整),但这取决于坏值的类型。例如,如果您创建了一个仅允许字符串的函数,而用户输入了一个整数,那么您就会TypeError改为输入整数。如果用户输入了错误的输入(意味着它具有正确的类型,但不符合某些条件), aValue Error将是您的最佳选择。ValueError 还可以用于阻止程序出现其他异常,例如,您可以使用 aValueError来阻止 shell 表单引发 a ZeroDivisionError,例如在此函数中:
def function(number):
if not type(number) == int and not type(number) == float:
raise TypeError("number must be an integer or float")
if number == 5:
raise ValueError("number must not be 5")
else:
return 10/(5-number)
Run Code Online (Sandbox Code Playgroud)
PS 有关 python 内置异常的列表,请访问此处: https: //docs.python.org/3/library/exceptions.html(这是官方的 python 数据库)