Home > front end >  Type Hinting List of Strings
Type Hinting List of Strings

Time:02-17

In python, if I am writing a function, is this the best way to type hint a list of strings:

def sample_def(var:list[str]):

CodePudding user response:

I would use the typing module

from typing import List

def foo(bar: List[str]):
    pass

The reason is typing contains so many type hints and the ability to create your own, specify callables, etc. Definitely check it out.

Edit:
I guess as of Python 3.9 typing is deprecated (RIP). Instead it looks like you can use collections.abc.*. So you can do this if you're on Python 3.9 :

from collections.abc import Iterable

def foo(bar: Iterable[str]):
    pass

You can take a look at https://docs.python.org/3/library/collections.abc.html for a list of ABCs that might fit your need. For instance, it might make more sense to specify Sequence[str] depending on your needs of that function.

  • Related