×

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

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

Python BytesIO

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands....

5 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Anaconda python 3.7 download for windows 10 64-bit

Before installing Anaconda, you need to first know what Anaconda actually is. Anaconda is an IDE (Integrated development environment) platform used to code and executes python programs. Anaconda works both online...

3 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.