×

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 String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

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 uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python Dictionary clear() method

Python Dictionary clear() method The dictionary.clear() method in Python removes all the elements from a dictionary. Syntax dictionary.clear() Parameter NA Return None Example 1 # Python program explaining # the dictionary.clear() method # initialising the dictionary fruits =...

1 minute read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute 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.

Python List clear() method

Python List clear() method The list.clear () method in Python extends the list by appending all the items from the iterable. Syntax list.clear() Parameter NA Example 1 # Python Program explaining # the list.clear() method week_list = ["Monday", "Tuesday", "Wednesday","Thursday","Friday",...

1 minute read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python delattr() function

Python delattr() function The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object. Syntax delattr(object, name) Parameter object : This parameter represents the object from which...

1 minute read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.