Advanced Typing in Python

Lesson Introduction

Welcome to this lesson on Advanced Typing in Python! Today, we'll explore how to make our Python code more robust and readable using advanced typing features. These features help make code clearer, catch errors early, and improve overall quality.

Ready to dive in? Let's go!

Optional Typing

Sometimes, a function might return a value, or it might return nothing (None). In such cases, we use Optional from the typing module. This makes our intentions clear.

Here’s a function that tries to find a string in a list. If it finds the string, it returns it; if not, it returns None.

from typing import Optional

def find_string(strings: list[str], target: str) -> Optional[str]:
    for string in strings:
        if string == target:
            return string
    return None

if __name__ == "__main__":
    my_strings = ["apple", "banana", "cherry"]
    target = "banana"
    result = find_string(my_strings, target)

    if result:
        print("Found:", result)  # Found: banana
    else:
        print("String not found")  # String not found

The return type Optional[str] shows the function could return a str or None.

Union Typing

Sometimes, a value can be more than one type. For example, a function parameter might be an int or a float. We use Union to handle this.

Here's a function that takes a number, which can be either an int or a float, processes it, and returns a float.

from typing import Union

def process_number(value: Union[int, float]) -> float:
    return value * 2.5

if __name__ == "__main__":
    num = 10
    print("Processed Value:", process_number(num))  # Processed Value: 25.0

    num = 10.5
    print("Processed Value:", process_number(num))  # Processed Value: 26.25

Using Union[int, float] makes it clear the function accepts either type.

Tuple Typing

Another useful typing feature is Tuple. Sometimes, a function needs to return multiple values as a single compound value. This can be done using a Tuple from the typing module.

Here's an example where a function returns a pair of values, a str and an int:

from typing import Tuple
import random

def get_random_name_and_age() -> Tuple[str, int]:
    name = random.choice(["Alice", "Bob", "Ann", "John"])
    age = random.randint(18, 40)
    return name, age

if __name__ == "__main__":
    name, age = get_random_name_and_age()
    print(f"Name: {name}, Age: {age}")  # Example output: Name: Alice, Age: 30

The return type Tuple[str, int] makes it clear that the function returns a tuple containing a str and an int.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal