Typing Module vs Built-in Types: Which to Use?

What is the Difference Between Using List, Tuple, etc., from the typing Module vs. Directly Referring to Types in Python?

What’s the difference between using List, Tuple, and other types from the typing module, like in the following example?

from typing import Tuple

def f(points: Tuple):
    return map(do_stuff, points)

Versus directly referring to Python’s built-in types:

def f(points: tuple):
    return map(do_stuff, points)

When should I use List, Tuple, etc., from the typing module as in Python typing tuple, and when is it better to directly use list, tuple, or other built-in types?

Hey @suneelak.673 Hope you are doing great,

Here is a detailed explanation of the above question:-

Use the typing module for Type Hinting in Function Signatures. When working with static type checkers like mypy, using python typing tuple (e.g., Tuple[int, int]) allows for better documentation, precise type hints, and improved code completion. This doesn’t impact runtime behavior but provides clarity for developers and tools.

Example:

from typing import Tuple  

def f(points: Tuple[int, int]):  
    return map(do_stuff, points)  

Here, the Tuple from the typing module explicitly defines the types of elements in points. It’s great for static analysis tools to ensure correctness."

Use Built-In Types When Simplicity is the Goal. If you’re not using static type checkers or working on a simple script, Python’s built-in tuple is sufficient and avoids unnecessary imports. It’s clean, straightforward, and perfectly valid in most scenarios.

Example:

def f(points: tuple):  
    return map(do_stuff, points)  

For smaller projects, there’s no need to overcomplicate things with python typing tuple. The built-in tuple works fine without dependencies, making your code cleaner and easier to read.

Here is the answer:-

Use Built-In Types with Generics in Python 3.9+ for Conciseness. Starting with Python 3.9, you no longer need to rely on the typing module for generics. You can directly use built-in types like tuple with type hints, which makes the syntax more modern and maintainable.

Example (Python 3.9+):

def f(points: tuple[int, int]):  
    return map(do_stuff, points)  

Here, the built-in tuple supports type hints without requiring an explicit typing import. This updated syntax keeps your code clean and modern, while still achieving the benefits of python typing tuple.