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!
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
.
Sometimes, a value can be more than one type. For example, a function parameter might be an or a . We use to handle this.
