debugpythonCriticalCanonical
Which exception should I raise on bad/illegal argument combinations in Python?
Viewed 0 times
pythonillegalshouldargumentraiseexceptioncombinationswhichbad
Problem
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:
The only annoyance with this is that every package has its own, usually slightly differing
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.
"""
passThe 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?Solution
I would just raise ValueError, unless you need a more specific exception..
There's really no point in doing
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?Code Snippets
def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")Context
Stack Overflow Q#256222, score: 933
Revisions (0)
No revisions yet.