Where can I find what exceptions are thrown from Python built-in modules?

I am writing a decorator to test some functionality. I try to use inline modules as much as possible to make the heavy lifting, but I am stuck on what kind of exceptions I should catch when using them.

For example:

def Validated(fun):
    def ValidatedFun(*args, **kwargs):
        try:
            _ = dict(kwargs.get('untrusted_data', ()))
        except ? as e:
            raise BetterError('Additional relevant info') from e
        return fun(*args, **kwargs)
    return ValidatedFun

      

I'd like to know:

  • What are the most derived exceptions that dict

    (and other built-in ones) explicitly raise?
  • Where can I find documentation that lists them? (they are not included https://docs.python.org/ )
+3


source to share


2 answers


All standard Python types follow the default few exception conventions. The behavior is documented for exceptions , not types.

To dict

exclude TypeError

and ValueError

. There is another exception which can be raised at this point, but they do not depend on the input ( MemoryError

and KeyboardInterrupt

).



TypeError

indicates that the type of the passed object is not supported; documentation of dict

what types are accepted (collation or iterables), everything else raises the exception. Accepted types must meet certain expectations; if they fail, it is generated ValueError

(correct type but value incorrect).

+6


source


the list of exceptions cannot be set by a specific python function. This is due to the typing of the duck python. Since you could provide objects of any type as parameters to your function, and since those functions could do what they want in their implementation, any exception could in principle be raised. Usually it is clear in the docs what kind of exception they raise under certain conditions (for example, an IOError when a file is not found), but this is different from "listing all the exceptions that a function can take".

I would also advise your strategy to forward exceptions to "BetterError" as you plan, as this hides the original cause and location where the error first occurred. If you really want to provide better error messages, do argument validation at the beginning of your function and raise ValueErrors for situations that cannot be ruled out but would throw any line-by-line exception:



if not is_valid_data(untrusted_data) :
    raise ValueError("invalid input")
unused_dict = dict(untrusted_data)

      

+1


source







All Articles