[英]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:在 python 中,如果我正在编写 function,这是键入提示字符串列表的最佳方式:
def sample_def(var:list[str]):
I would use the typing
module我会使用typing
模块
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.原因是typing
包含如此多的类型提示以及创建自己的、指定可调用对象等的能力。一定要检查一下。
Edit:编辑:
I guess as of Python 3.9 typing
is deprecated (RIP).我想从 Python 开始,不推荐使用 3.9 typing
(RIP)。 Instead it looks like you can use collections.abc.*
.相反,您似乎可以使用collections.abc.*
。 So you can do this if you're on Python 3.9+:因此,如果您使用的是 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.您可以查看https://docs.python.org/3/library/collections.abc.html以获取可能适合您需要的 ABC 列表。 For instance, it might make more sense to specify Sequence[str]
depending on your needs of that function.例如,根据您对 function 的需求来指定Sequence[str]
可能更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.