Python return type annotations

Question:

When declaring a function, should we use return annotations?

def generate_nine() -> int:
    return 9

Or can we simply put something like this:

def generate_nine():
    return 9
Asked By: Juan Alegría

||

Answers:

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

There’s no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.

DOCS

Answered By: Kuldeep Singh Sidhu

Yes, You should write return type annotation for writing cleaner code. It’s been said that return type annotation enhanced code readability. Consider an example

For example:

   def get_data(a):
       return a ** 2

It is not easier for anyone, what is the expected return type.
If the incoming data is float, the function will return float.
If the function receive int value, it will return int. So even it is not easier to read.

So for better understanding it is being recommended to write both arguments type and return type while writing. See the below example:

def greeting(name: str) -> str:
    return 'Hello ' + name

In the function greeting, the argument name is expected to be of type str and the return type str. Subtypes are accepted as arguments. The compiler will raise an error if it is not expecting a string value.

The code is much clear and understandable compare to the previous one. So to summarize, for writing cleaner code we should add return type annotation. Please see this docs for better understanding

Answered By: Tarequzzaman Khan