Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Function Annotations in Python
    python

    Function Annotations in Python

    April 2, 2023No Comments4 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Annotations for Python Functions

    Annotations on functions can be written as arbitrary expressions and evaluated alongside the functions at compile time. At runtime, they do not exist, and these expressions have no significance in Python. A third party application or external python libraries utilizes and interprets them.

    We all know that third-party libraries make use of function annotations due to the benefits that these annotations provide. For

    example:


    1. Function annotations with strings

      can be used as messages at compile time to describe the functionality of different methods, classes and variables.

    2. [def fxn(a:”int”, b:”float”=5.0) -> “int”]

    Since python provides dynamic type checking, and since there is no method to check the return type or the data type, these annotations can be used to declare the data types of the parameters in the aforementioned example. These are used by mypy and other libraries.

    annotations.

    Syntax for the function annotations

    Many different forms of function annotations are possible, including: 1. Annotating functions with only a few parameters:



    1. def


      functionName(argumentName : expression):

    After the name of the argument, we can use a colon, and then write the expression following the colon. Any valid argument data type or message string can be used in the expression. Case in point:



    1. def


      fxn(var1 : expression1,var2:expression2:


      96


      ):

    2. Annotations for functions that take in too many parameters:

    This method of annotating functions allows us to specify an arbitrary number of arguments with the same expression as function parameters. Case in point:



    1. def


      fxn(*arg1: expression1,**arg2:expression2):

    3. Parameter nesting function annotation:

    Function annotations must be applied to each individual element of the list if it is to be used as an argument in a function call. Case in point:



    1. def


      fxn((var1:expression,var2:expression),(var3:expression,var4:expression)):

    4. Return type annotations for functions:

    The ‘->’ operator is used to annotate the return type. Case in point:



    1. def


      fxn(var1:expression) -> expression2:

    The following explains how to make sense of Python’s function annotations:

    example:

    Example:

    Resulting



    1. # program to print Fibonacci series using function annotations





    2. def


      fibonacci(n:


      ‘int’


      , res:


      ‘list’


      =[])->


      ‘list’


      :



    3. if


      n ==


      0


      :



    4. return


      res



    5. else


      :



    6. if


      len(res)<


      2


      :


    7. res.append(

      1


      )


    8. fibonacci(n-

      1


      , res)



    9. else


      :


    10. last = res[-

      1


      ]


    11. second_last = res[-

      2


      ]


    12. res.append(last + second_last)

    13. fibonacci(n-

      1


      , res)



    14. return


      res



    15. print


      (fibonacci(


      8


      ))

    Function Annotations in Python Clarification:

    The function for determining the initial n Fibonacci numbers is presented above in bold. The function expects n and a blank list as input and produces the corresponding list as output.

    We’ve specified that n is an integer and that res is a list in the function’s documentation. The return type was also specified via function annotation.

    list.

    Note: we can access all the function annotations we used in the function by various methods:

    1. “__annotations__” in action:

    Annotations within a function can be retrieved using the __annotations__ attribute. It gives back the dictionary with the key being the parameters and the value being the actual values of those arguments.

    expression.

    Example 2:

    Resulting



    1. # Python program to print Fibonacci series using function annotations and to access the annotations





    2. def


      fibonacci(n:


      ‘int’


      , res:


      ‘list’


      =[])->


      ‘list’


      :



    3. if


      n ==


      0


      :



    4. return


      res



    5. else


      :



    6. if


      len(res)<


      2


      :


    7. res.append(

      1


      )


    8. fibonacci(n-

      1


      , res)



    9. else


      :


    10. last = res[-

      1


      ]


    11. second_last = res[-

      2


      ]


    12. res.append(last + second_last)

    13. fibonacci(n-

      1


      , res)



    14. return


      res



    15. print


      (fibonacci(


      8


      ))



    16. print


      (fibonacci.__annotations__)

    :

    Explanation: Function Annotations in Python

    Annotations for functions were used in the preceding code to generate the first list of n Fibonacci digits.

    We also used the ‘__annotations__’ property to output the function annotation, and the result was a dictionary. 2. Typical Python Module Use:

    To obtain the function annotations in Python, you can utilize the built-in pydoc package.

    The pydoc.help() function creates a shell in which we may retrieve any file’s documentation, as well as the annotations for any function. 3. The Inspect Module in Action

    Another one of Python’s built-in modules goes by the moniker “inspect.” Any file, module, class, or object can have its details displayed by this module.

    There are a variety of data-gathering tools available. The getfullargspec method in the inspect module will be used to retrieve the function annotation details and any other relevant information.

    information.

    Example 3:

    Final Product:



    1. # Python program to print Fibonacci series using function annotations





    2. import


      inspect



    3. def


      fibonacci(n:


      ‘int’


      , res:


      ‘list’


      =[])->


      ‘list’


      :



    4. if


      n ==


      0


      :



    5. return


      res



    6. else


      :



    7. if


      len(res)<


      2


      :


    8. res.append(

      1


      )


    9. fibonacci(n-

      1


      , res)



    10. else


      :


    11. last = res[-

      1


      ]


    12. second_last = res[-

      2


      ]


    13. res.append(last + second_last)

    14. fibonacci(n-

      1


      , res)



    15. return


      res



    16. print


      (fibonacci(


      8


      ))



    17. print


      (inspect.getfullargspec(fibonacci))

    Explanation: Function Annotations in Python

    By calling getfullargspec in the aforementioned code, we were able to obtain comprehensive information about the method, including the function’s annotation.

    Function Annotations in Python Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticlePython Tuple Quiz
    Next Article Python Variables and Data Types Quiz

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.