简体   繁体   中英

Type Hinting List of Strings

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]):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM