问题描述
我想知道在Python中指示无效参数组合的最佳实践。我遇到了一些这样的功能:
def import_to_orm(name,save = False,recurse =
$ b
:参数名称:要导入的外部实体的名称
:param save:返回前保存ORM对象
:param recurse:因为
需要原始对象有一个关键字,所以save必须是
`True`用于递归为'True'
:raise
$
$ / code $ <$ $ $ $ $ $ $ $ $ $ >
唯一的烦恼是每个包都有自己的,通常略有不同 BadValueError
。我知道在Java中存在 java.lang.IllegalArgumentException
- 很明白,每个人都将创建自己的 BadValueError
s在Python或还有另一个首选方法?
解决方案我只是提高,除非您需要更具体的例外。
def import_to_orm(name,save = False,recurse = False):
如果递归而不保存:
raise ValueError(save must be True如果递归为True)
真的没有意义, class BadValueError ValueError):pass
- 您的自定义类与,那么为什么不使用它?
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:
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
The only annoyance with this is that every package has its own, usually slightly differing BadValueError
. I know that in Java there exists java.lang.IllegalArgumentException
-- is it well understood that everybody will be creating their own BadValueError
s in Python or is there another, preferred method?
解决方案 I would just raise ValueError, unless you need a more specific exception..
def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")
There's really no point in doing class BadValueError(ValueError):pass
- your custom class is identical in use to ValueError, so why not use that?
这篇关于我应该在Python中提出错误/非法参数组合的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!