字符串类型提示列表

Che*_*sea 6 python var function python-typing

在 python 中,如果我正在编写一个函数,这是输入提示字符串列表的最佳方式:

def sample_def(var:list[str]):

Chr*_*sso 13

我会使用该typing模块

from typing import List

def foo(bar: List[str]):
    pass
Run Code Online (Sandbox Code Playgroud)

原因是typing包含如此多的类型提示以及创建自己的类型提示、指定可调用项等的能力。一定要检查一下。

编辑:
我想 Python 3.9typing已被弃用(RIP)。相反,看起来您可以使用collections.abc.*. 因此,如果您使用的是 Python 3.9+,则可以执行此操作:

from collections.abc import Iterable

def foo(bar: Iterable[str]):
    pass
Run Code Online (Sandbox Code Playgroud)

您可以查看https://docs.python.org/3/library/collections.abc.html,获取可能适合您需求的 ABC 列表。例如,Sequence[str]根据您对该功能的需求进行指定可能更有意义。