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

Time:07-19

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?

CodePudding user response:

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)

CodePudding user response:

If you want paths to be just a string then,

def some_function(paths: str):

If you want the function to accept any number of strings you can use the * operator

def some_function(*paths: str):

Keep in mind type hinting is only a suggestion, python will not test for correct input argument type.

  • Related