Search code examples
pythonfunctionpython-typing

Python return type annotations


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

Solution

  • Yes, you should write return type annotations for writing cleaner code. It's been said that return type annotations enhance code readability.

    For example:

    def get_data(a):
        return a ** 2
    

    It is not easy to know what is the expected return type.
    If the incoming data is float, the function will return an float.
    If the function receives an int param, it will return an int.

    So for better understanding it is recommended to write both argument types and return types for functions. See the example below:

    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. Python will raise an error if it is not expecting a string value.

    The code is much clearer and understandable compared to the previous one. So to summarize, for writing cleaner code we should add return type annotations. Please see these docs for better understanding.