×

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

Hog Descriptor Opencv Python

Python programming language: 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...

3 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

4 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

How to Convert A List into String In Python?

How to Convert A List into String In Python? List is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets...

3 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Python Skyline

Python Programming Language: 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...

3 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 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.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.