Python type hinting with exceptions

25,392

Solution 1

Type hinting can't say anything about exceptions. They are entirely out of scope for the feature. You can still document the exception in the docstring however.

From PEP 484 -- Type Hints:

Exceptions

No syntax for listing explicitly raised exceptions is proposed. Currently the only known use case for this feature is documentational, in which case the recommendation is to put this information in a docstring.

Guido van Rossum has strongly opposed adding exceptions to the type hinting spec, as he doesn't want to end up in a situation where exceptions need to be checked (handled in calling code) or declared explicitly at each level.

Solution 2

It is usually a good idea to document the error. This means that another developer using your function will be able to handle your errors without having to read through your code.

Share:
25,392
Yuval Pruss
Author by

Yuval Pruss

Full Stack Developer at C4 Secutrity

Updated on July 05, 2022

Comments

  • Yuval Pruss
    Yuval Pruss almost 2 years

    I have a function that looks like this:

    def check_for_errors(result):
        if 'success' in result:
            return True
    
        if 'error' in result:
            raise TypeError
    
        return False
    

    In successful run of this function, I should get a bool, but if there is an error I should get a TypeError- which is OK because I deal with it in another function.

    My function first line looks like this:

    def check_for_errors(result: str) -> bool:
    

    My question is: Should I mention the error in my type hinting?

  • Erik Aronesty
    Erik Aronesty over 4 years
    Or the use case of checking that you're not implicitly raising weird exceptions people don't expect
  • Martijn Pieters
    Martijn Pieters over 4 years
    @ErikAronesty: Define weird. All code can raise MemoryError, and most code can raise KeyboardInterrupt. A good linter can help you better understand exceptions than type hinting can.
  • Eduard Grigoryev
    Eduard Grigoryev over 4 years
    And what if an exception is returned, not raised? E.g. NotImplemented can be returned.
  • Martijn Pieters
    Martijn Pieters over 4 years
    @EduardGrigoryev: NotImplemented is not an exception, it is a singleton object, a special flag value. You are thinking of NotImplementedError. Exceptions can still be returned, exceptions are just classes that are subclassing BaseException, so you can use Type[BaseException] to type hint a function that accepts or returns exception classes, for example.
  • shaunc
    shaunc almost 4 years
    Is there something like typescript never to declare you always raise a error? typescriptlang.org/docs/handbook/basic-types.html#never
  • Martijn Pieters
    Martijn Pieters almost 4 years
    @shaunc: yes: typing.NoReturn.