Python3 new feature Function annotation Function Annotations Usage Analysis, python3annotations

Source: Internet
Author: User

Python3 new feature Function annotation Function Annotations Usage Analysis, python3annotations

This article analyzes the usage of Function Annotations for new features of python3. We will share this with you for your reference. The details are as follows:

Python 3. X adds a Feature called Function Annotations.

Although its purpose is not a rigid syntax-level requirement, it can be used as an additional comment for functions as its name suggests.

Common functions in Python are defined as follows:

def func(a, b, c):  return a + b + c>>> func(1, 2, 3)6

Functions Added with function comments are in the following format:

def func(a: 'spam', b: (1, 10), c: float) -> int:  return a + b + c>>> func(1, 2, 3)6

The general rule for annotation is that the parameter name is followed by a colon (:) and then an expression. This expression can be in any form.

The return value is in the form of-> int. annotation can be saved as the attributes of the function.

To view all annotation statements, run the following statement:

>>> func.__annotations__{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}

If you add comments to the function, can you continue to use the default parameters? The answer is yes.

>>> def func(a: 'spam' = 4, b: (1, 10) = 5, c: float = 6) -> int:...  return a + b + c...>>> func(1, 2, 3)6>>> func()15>>> func(1, c=10)16>>> func.__annotations__{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.