Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

It would be better to raise ValueError unless you need a more specific exception below is the code that explains how we will:-

def import_to_orm(name, save=False, recurse=False):

         if recurse and not save:

                raise ValueError("save must be True if recurse is True")

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...