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
BadValueErrors 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?
I would inherit from
class IllegalArgumentError(ValueError): pass
It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.
If you need to catch that specific error, it is helpful to have a name.