简体   繁体   中英

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

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

Python 3 automatically managed return type. So I think, it is obvious to write return type.
For instance, I write a function below that return an integer:

   def generate_nine_int():
       return 9
   print(type(generate_nine_int()))

this function return an integer. The print function print <class 'int'>

similarly, for a floating-point number, I wrote another function:

   def generate_nine_float():
       return 9.2
   print(type(generate_nine_float()))

When I print this function this will print <class 'float'>

Similarly for string, dictionary, list etc. the return type is automatically managed by Python 3. So I don't think you need to write return type while creating the functions. So you could be used your second function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM