Course contentsShow
← Python
Lesson 555 of 1,0609. Type Safety and Code QualityFree lesson

Working with Homogeneous Collection Types

You will master using the typing module to annotate lists, sets, and tuples that contain elements of a single specific type.

Mastering Homogeneous Collection Types

In this lesson, you will learn how to use the typing module to enforce type safety by ensuring that collections—like lists, sets, and tuples—contain only elements of a specific, consistent type.

When you define a variable as a list or a set, Python’s default behavior is to treat them as generic containers. This means a list could accidentally hold both integers and strings, leading to potential bugs later in your code when you try to perform arithmetic or string manipulation on the wrong items. To prevent this, we use the typing module to annotate "homogeneous" collections.

Annotating Collections

To specify that a collection should only contain a specific type, you use the bracket syntax [] provided by the typing module. For example, if you have a list of user IDs, you want to ensure they are all integers.

from typing import List, Set, Tuple

# A list that should only contain integers
user_ids: List[int] = [101, 102, 103]

# A set that should only contain strings
allowed_roles: Set[str] = {"admin", "editor", "viewer"}

# A tuple that should only contain floats
coordinates: Tuple[float, ...] = (10.5, 22.3, 45.1)

In the examples above:

  • List[int] tells static type checkers that every item in the list must be an int.
  • Set[str] ensures the set only contains str values.
  • Tuple[float, ...] uses an ellipsis (...) to indicate that the tuple can have an arbitrary number of elements, but every single one of them must be a float.

By explicitly defining the contents of your collections, you make your code more predictable. If a developer later tries to append a string to user_ids, tools like mypy will immediately flag it as a type violation, allowing you to catch errors before the code even runs. This practice shifts the burden of validation from runtime to development time, significantly improving your project's overall code quality.

Key Takeaway: Use the typing module to annotate your collections with brackets (e.g., List[int]) to ensure your data structures remain homogeneous and type-safe.