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.
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.
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:
The return type Tuple[str, int] makes it clear that the function returns a tuple containing a str and an int.
