×

Function annotations() in Python

What is Function Annotations?

Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution. These annotations do not have any meaning in Python. Function annotations are completely choice for return value and parameters.

Function annotations are added to Python as PEP-3107. PEP stands for Python Enhancement Proposal. The main reason for having annotations in Python is for linking metadata to function that returns value and parameters.

Syntax:

As we mention above, parameters are optional for parameter name in Python.

So, we are using word ‘expression’ is a type of parameter that can be use by external libraries in arbitrary string.

Annotations of simple parameters:

We use argument name as ‘:’ which is given by the expression. Syntax for annotation can be expressed as:

def foo (a: statement, b: statement = 8):

Annotations for excess parameters:

Excess parameter will perform arbitrary number of arguments to be sent in a function call. Examples for excess parameter are args and kwargs. Excess parameter syntax has shown below:

def foo(*args: statement, *kwargs: statement):

Annotations for nested parameters:

Nested parameters are used when a tuple is called in a function call then the feature of Python 2x will automatically open. Where as in Python 3x, it is removed and when it requires, we can open it manually.

Syntax for nested parameters before tuple as shown below:

def foo ((a: expression, b: expression), (c: expression, d: expression)):

Annotations for return type:

In return type annotations, ‘->’ sign is used which is further passed by ‘:’. Annotation return type is different from function arguments. Return type annotation syntax has shown below:

def foobar (a: statement)->statement:

Example program for function annotations:

// Python program to demonstrate Fibonacci series
deffib(j:'int', output: ‘list'= [])-> 'list':
    ifj ==0:
        returnoutput
    else:
        iflen(output)< 2:
            output. append (1)
            fib (j-1, output)
        else:
            last =output [-1]
            second last =output [-2]
            output. append (last +second_last)
            fib (j-1, output)
        returnoutput
print (fib (8))

Output:

[1, 1, 2, 3, 5, 8]

Default Arguments:

//Default arguments program has shown below
def foobar(j: 'an argument that defaults to 5' = 5):  
   print(j)


 foobar(7)
 7


foobar() 
5

Accessing Function Annotations

  • Using ‘_annotations_’:

    The function annotations from the above codes can be accessed to allocate ‘_annotations_’. We use a special keyword ‘return’ for display an output. The following code will print the annotations.
//Python program to demonstrate function annotations: 
deffib(j:'int', output:'list'=[])-> 'list':
    ifj ==0:
        returnoutput
    else:
        iflen (output)< 2:
            output. append (1)
            fib (j-1, output)
        else:
            last =output [-1]
            second_last =output [-2]
            output. Append (last +second_last)
            fib (j-1, output)
        returnoutput
print(fib. __annotations__)

Output:

{‘return’: ‘list’, ‘j’: ‘int’, ‘output’: ‘list’}
  • Using standard module ‘pydoc’:

    The ‘pydoc’ is a primary Python module that gives documentation inside a Python module. It has a special ‘help ()’ method that gives help to the methods or keywords. The ‘help ()’ method is used in function annotation.
  • Using standard module ‘inspect’:

    The ‘inspect’ module gives useful functions to help the information about live objects. Examples for standard modules are classes, functions, modules, methods, code objects etc. The ‘getfullargspec’ method is used to get complete information about the function which has function annotations.
//Python program to demonstrate function annotations
importinspect
deffib(j:'int', output: ‘list'=[])-> 'list':
    ifj ==0:
        returnoutput
    else:
        iflen(output)< 2:
            output. append (1)
            fib(j-1, output)
        else:
            last =output[-1]
            second_last =output[-2]
            output. append (last +second_last)
            fib(j-1, output)
        returnoutput
print (inspect. getfullargspec(fib))

Output:

FullArgSpec(args=['n', 'output'], varargs=None,
 varkw=None, defaults=([], ), kwonlyargs=[],
kwonlydefaults=None, annotations=
{'output': 'list', 'return': 'list', 'n': 'int'})

Related Topics

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Excel Automation with Python

Data analysis is the upcoming technology in the IT sector; this data analysis can be performed easily with the help of data frames or by using excel sheets. The data...

4 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Python and its advantages

What is Python? Python is an object-oriented programming language, a general-purpose programming language with a high level, and also an interpreted language that has an easy syntax and dynamic semantics. Python...

7 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Exrex Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster...

4 minutes read.