我应该提高对在Python坏/非法参数组合哪个异常? [英] Which exception should I raise on bad/illegal argument combinations in Python?

查看:263
本文介绍了我应该提高对在Python坏/非法参数组合哪个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道指示在Python无效的参数组合的最佳实践。我已经遇到,你有一个函数像这样一些情况:

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

这个唯一的烦恼是,每个包都有自己的,平时略有不同 BadValueError 。我知道,在Java中存在 java.lang.IllegalArgumentException异常 - 这是很好理解,每个人都将是创建他们自己的 BadValueError S IN Python或有另一种,preferred方法?

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 BadValueErrors in Python or is there another, preferred method?

推荐答案

我只想养的 ValueError错误,除非你需要一个更具体的异常。

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")

有真的这样做没有意义的类BadValueError(ValueError错误):通过 - 自定义类是在使用中的 ValueError错误,为什么不能使用?

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坏/非法参数组合哪个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆