Programmer Coding

Function Annotations in Python

Function Annotations

Python’s function description feature allows you to add annotations about the elements declared in the definition and the type of data returned.

Although you can use Python’s data string functions to write functions, this function may fail if there are some changes to the template. Thus, thanks to PEP 3107.

The Python interpreter ignores annotations when executing functions. They are often used in Python IDEs to provide detailed information to programmers.

An expression is a valid Python expression appended to a parameter or returned data. The simplest example of annotation is defining a data type index. An annotation is called an expression after a colon is placed in front of the parameter

Example

def myfunction(a: int, b: int):

c = a+b

return c

Note that Python is a dynamically typed language and does not restrict any type checking during execution. Therefore, annotating parameters with a data type during a function call has no effect. Even if the argument number is not given, Python will not detect the error.

Example

def myfunction(a: int, b: int):

c = a + b

return c

# Calling the function with integer arguments

print(myfunction(10, 20))

# Attempting to call the function with string arguments

# This will raise a TypeError since the function expects integer arguments

print(myfunction(“Hello “, “Ramkrishna Kumar”))

Output

30

Hello Ramkrishna Kumar

Function Annotations With Return Type

Annotations are ignored at runtime, but are useful for the IDEs and static type checker libraries consisting of mypy.

you could deliver annotation for the return statistics type as well. After the parentheses and before the colon symbol, placed an arrow (->) observed by means of the annotation. as an example –

def myfunction(a: int, b: int) -> int:

c = a+b

return c

Function Annotations With Expression

As the use of the records type as annotation is ignored at runtime, you could positioned any expression which acts because the metadata for the arguments. for this reason, characteristic might also have any arbitrary expression as annotation as in following example –

Example

def total(x : ‘marks in Physics’, y: ‘marks in chemistry’):

return x+y

Function Annotations With Default Arguments

if you need to specify a default argument at the side of the annotation, you want to position it after the annotation expression. Default arguments have to come after the desired arguments within the argument listing.

Example

def myfunction(a: “physics”, b:”Maths” = 20) -> int:

c = a+b

return c

print (myfunction(10))

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top