Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting with exceptions

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?

like image 564
Yuval Pruss Avatar asked May 31 '17 10:05

Yuval Pruss


People also ask

Should I use type hinting in Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

Are Python type hints enforced?

Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.

What is type hinting Python?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.

Do Python type hints throw error?

If you indicate (with type hinting) that a variable is going to store a string, but you assign it to a boolean, your code is going to run without any error, because that's how it works in Python, but the code editor is going to yell at me.


Video Answer


1 Answers

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.

like image 75
Martijn Pieters Avatar answered Oct 13 '22 19:10

Martijn Pieters