Skip to content

Python Type Annotation

  • by

Python Type Annotations are a way to specify the types of variables, function parameters, and return values in Python code.

They are not enforced at runtime but provide useful information for developers and tools like type checkers and code editors to catch potential type-related errors and improve code readability. Type annotations were introduced in Python 3.5 and later versions.

Type annotations use the colon (:) syntax to specify the type of a variable or function parameter, and the -> syntax to specify the return type of a function. The most common types used in annotations include built-in types like int, str, float, bool, as well as user-defined classes and more advanced types from the typing module.

Here’s the syntax for various type annotations in Python:

1. Annotating variables:

variable_name: type = value

2. Annotating function parameters and return type:

def function_name(param1: type1, param2: type2, ...) -> return_type:
    # function body

3. Annotating function variables (inside the function body):

def function_name(param1: type1, param2: type2) -> return_type:
    variable_name: type
    # function body

4. Annotating with more complex types (using the typing module):

from typing import List, Tuple, Dict, Union

variable_name: List[int] = [1, 2, 3]
variable_name: Tuple[str, int] = ("hello", 42)
variable_name: Dict[str, float] = {"pi": 3.14159, "e": 2.71828}
variable_name: Union[int, float] = 42

5. Annotating with Optional types (from the typing module):

from typing import Optional

variable_name: Optional[int] = None

6. Annotating with custom classes and types:

class MyClass:
    pass

variable_name: MyClass = MyClass()

# Type aliases (using the `typing` module)
from typing import List

MyList = List[int]
variable_name: MyList = [1, 2, 3]

Type annotations can be used for any Python object, not just function parameters and variables. Additionally, Python allows you to use type hints in combination with default values for function parameters:

def function_name(param1: type1 = default_value1, param2: type2 = default_value2) -> return_type:
    # function body

Note: Annotations are optional and not enforced by the Python interpreter. They are primarily used to provide information to developers and tools for better code analysis, readability, and maintainability. For type-checking enforcement, you can use external tools like mypy.

Python Type Annotation example

Here are some examples of type annotations in Python:

Annotating variables:

# Basic type annotation
name: str = "John"
age: int = 30
height: float = 1.75
is_student: bool = True

Annotating function parameters and return type:

def add_numbers(x: int, y: int) -> int:
    return x + y

def greet_person(name: str) -> str:
    return "Hello, " + name

def calculate_average(numbers: List[float]) -> float:
    return sum(numbers) / len(numbers)

Complex example

from typing import List, Tuple

def calculate_average(numbers: List[float]) -> float:
    """Calculate the average of a list of numbers."""
    return sum(numbers) / len(numbers)

def greet_user(name: str) -> str:
    """Generate a greeting message."""
    return f"Hello, {name}!"

def merge_lists(list1: List[int], list2: List[str]) -> List[Tuple[int, str]]:
    """Merge two lists of different types into a list of tuples."""
    if len(list1) != len(list2):
        raise ValueError("Both lists should have the same length.")

    return [(list1[i], list2[i]) for i in range(len(list1))]

# Usage of the functions with type-checked arguments
numbers = [1.2, 3.4, 5.6, 7.8]
result = calculate_average(numbers)
print(f"Average: {result}") 

name = "Alice"
greeting = greet_user(name)
print(greeting)

list1 = [1, 2, 3]
list2 = ["apple", "banana", "orange"]
merged_list = merge_lists(list1, list2)
print(merged_list)

Output:

Python Type Annotation

In this example, we have defined three functions, each with type annotations:

  1. calculate_average: This function takes a list of floats and returns a float (the average).
  2. greet_user: This function takes a string (name) and returns a string (a greeting).
  3. merge_lists: This function takes two lists, one of integers and another of strings, and returns a list of tuples containing pairs of elements from the two lists.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading