Function Annotations in Python

Function annotations are random expressions that are written with the functions and won’t be evaluated in the compile time. Moreover, the future annotation won’t exist at the run time. This article has listed in the future annotations in Python.

What are Future Annotations?

Function Annotations are the arbitrary Python expressions that will be associated with the various parts of functions. Hence, it won’t be checked at the compile time and doesn’t play any role during the existing time.

Moreover, function annotations are mostly used by third-party libraries as it is known that the different libraries have different benefits from these function annotations.

a.Future annotations with strings will work as messages at the compile time for describing the functionality of different methods, classes, and variables.

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

In the example provided above, these annotations will define the data types of the parameters as Python will support the dynamic type checking and it is not possible to return type. Thus, libraries will use these kinds of annotations.

What is the syntax of the Future Annotations?

a. Future Annotation for simple parameters

def functionName(argumentName : expression):  

Colons are used after the argument name and then we can write the expression after the colon. This expression will appear similar to any data type of the argument.

Example

def fxn(var1 : expression1,var2:expression2:96):  

b. Function annotations for excess parameters

if it is required to use an arbitrary number of arguments as the function parameters with the same expression. Hence, it is possible to use the function annotation.

Example

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

c. Function annotation for the nested parameters

If it is required to pass the list in the function call it as the argument and thus, apply the function annotations on the individual elements.

Example

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

d. Function annotation for the return type:

The annotation of the return time will be operated with the help of the’>’ operator.

Example

def fxn(var1:expression) -> expression2:  

What are the examples of Function annotation in Python?

The examples of function annotation in Python are given below:

def add_numbers(x: int, y: int) -> int:
    """
    Adds two numbers and returns the result.

    :param x: The first number.
    :param y: The second number.
    :return: The sum of x and y.
    """
    result = x + y
    return result

# Example usage:
num1 = 5
num2 = 7
sum_result = add_numbers(num1, num2)

print(f"The sum of {num1} and {num2} is: {sum_result}")

Output

The sum of 5 and 7 is: 12
  1.  Using ‘__annotations__’

The attribute __annotations__ will get every annotation in the function. It will return with the dictionary and has a pair of keys and values in which the key would act as an argument and the value will be in their expression.

def calculate_discount(original_price: float, discount_rate: float = 0.1) -> float:
    """
    Calculate the discounted price based on the original price and discount rate.

    :param original_price: The original price of the item.
    :param discount_rate: The discount rate (default is 10%).
    :return: The discounted price.
    """
    discounted_price = original_price - (original_price * discount_rate)
    return discounted_price

# Example usage:
item_price = 100.0
discounted_price = calculate_discount(item_price)

print(f"Original Price: ${item_price}")
print(f"Discounted Price: ${discounted_price}")

Output

Original Price: $100.0
Discounted Price: $90.0

b. Using the standard Python module:

In Python, there’s a module called pydoc that helps create documentation for Python code. While it doesn’t have a help() function to open a shell environment, you can still get information about function annotations.

c. Using the inspect module

In Python, there is another standard module which is known as inspect. This consists of information on a file, module, class, or object.

Example

import inspect

def example_function(x: int, y: str) -> float:
    return float(x)

# Get information about the function using inspect
function_info = inspect.getfullargspec(example_function)

# Print the information
print("Function Name:", example_function.__name__)
print("Parameters:", function_info.args)
print("Default Values:", function_info.defaults)
print("Annotations:", example_function.__annotations__)
print("Docstring:", example_function.__doc__)

Output

Function Name: example_function
Parameters: ['x', 'y']
Default Values: None
Annotations: {'x': <class 'int'>, 'y': <class 'str'>, 'return': <class 'float'>}
Docstring: None

Conclusion

To conclude, this article has described the Future Annotations in Python. It has also included the benefits of future annotations. This information can allow to improve skills and knowledge regarding the future annotation of Python.

Function Annotation in Python -FAQs

Q1. What is a function annotation in Python?

Ans. Function annotations will work for both parameters and return values, and are completely optional.

Q2. What is an annotation in Python?

Ans. In Python, annotations are like notes in the code that help give information about variables, what kind of data functions expect, and what they give back.

Q3.What is function typing annotation in Python?

Ans. A type annotation that is referred to as a type hint, is also an optional notation that specifies the type of a parameter or function result.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment