Search code examples
pythonpython-3.xtype-hinting

How to type hint an (arbitrary) collection of some data type in Python?


If I have a function similar to:

def some_function(paths):
    for path in paths:
        other_function(path)

what is the correct way to type hint paths? The intention of the function is that each object inside paths is a string, but obviously paths could be a list, tuple, set, numpy array, pandas Series etc. so the following seems too specific:

def some_function(paths: list[str]):
    for path in paths:
        other_function(path)

Should I be using either Collection or Sequence from the typing module?


Solution

  • Since the only thing you rely on here is iterability, ask for that.

    from typing import Iterable
    
    def some_function(paths: Iterable[str]):
        for path in paths:
            other_function(path)
    

    If these really are supposed to be file-system paths, you might tweak it to allow str or anything supporting the os.PathLike ABC:

    import os
    from typing import Iterable
    
    def some_function(paths: Iterable[str | os.PathLike]):  # On older Python, Iterable[Union[str, os.PathLike]]
        for path in paths:
            other_function(path)