In short, yes!
Python does support type annotations https://docs.python.org/3/library/typing.html, but, as stated in the documentation:
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
A few examples
def greeting(name: str) -> str:
return f'Hello {name}'
def square_root(number: float) -> float:
return number**.5
Catch fish errors with your friend linter!
Before going on with the boring stuff, let's see how type annotations can be helpful to catch and correct errors. Let's take a simple problem "calculate the square root of user's input".
As you can see from this example, we have an error in our code (a fairly common one in Python)! The main problem is that, to check the error, we have to run and test the code! Let's see what happens with type annotations.
Thanks to type annotations, the "linter" (in this case "mypy") is able to tell me that I have two problems in my code, without having to run it! The best part? The errors are way easier to understand!
let's compare the runtime error with linter's error:
Unsupported operand type(s) for ** or pow(): 'str' and 'float'
Argument 1 to "square_root" has incompatible type "str"; expected "float"
Not only the linter is able to catch the mistake, but it can also suggest how to fix it! It also catches another error: in the first case, I would have to correct the first mistake and run the code again to find out that I can't sum a string and a float (which makes sense), but thanks to type annotations, we know that:
Unsupported operand types for + ("str" and "float")
Now, let's take a look to the working code:
Quick note on linters
Up until now I've talked about linters, but what exactly is a linter? It's a software, a tool, which analyzes a project (or just a file) and tells the developer whether there are any problems! Problems can range from type mismatches (like in the above example) to hints on code style: variables aren't named correctly, or, for example, my linter tells me that a file shouldn't end with a blank line, or that there must be two blank lines between functions definitions. There are a lot of linters for Python, for more info check this article: https://realpython.com/python-code-quality/
Blazingly fast
Here's quick and fun a video in which the rich and powerful type system of Rust helps a developer write some code: I have a confession (by ThePrimeagen, one of my favorite tech youtubers)