1

If I have a python function with 2 optional parameters (for search criteria) but no one is provided (I need at least one parameter) what is the right exception to throw?

What if I only one of two parameters have to be passed? What exception to throw if two are provided? Or may be create two distinct functions?

Julian Popov
  • 17,401
  • 12
  • 55
  • 81

4 Answers4

4

TypeError is most appropriate - this is what you get usually.

theheadofabroom
  • 20,639
  • 5
  • 33
  • 65
4

You can find a list of the built in Python exceptions here, but remember you can always create your own kind of exception if none of these match what you're after.

I'd suggest using a TypeError (which is what you normally see in Python code being used). You could also use AssertionError, and asserting that at least one argument should be supplied to the function.

James Bedford
  • 28,702
  • 8
  • 57
  • 64
3

I would throw an informative TypeError:

if no_args or both_args:
    raise TypeError('f() must be passed exactly one of foo=value, bar=value')
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
3

Why not use assertion?

assert len(args) > 1, "At least one argument should be passed to the function"
Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
  • 1
    Assertions have a different abstract idea behind them; they shall help find programming errors early; you typically do not catch exceptions raised due to failed assertions. Exceptions on the other hand will often get caught later on by the calling code to handle the situation. You also have to keep in mind that assertions can be configured away so they do not get evaluated at all )option -O to the interpreter). If this is okay for this situation must be considered. – Alfe Sep 05 '12 at 09:57
  • Indeed. The idea of my answer was: if this is not a public API, but an internal function call, use assertion to make sure that the code is correct. – Zaur Nasibov Sep 06 '12 at 18:45
  • Agreed; if all ju. wanted was finding programming errors (may well be so) during development, then assert is a good approach. – Alfe Sep 07 '12 at 12:12