gpt4 book ai didi

python - 类型提示字符串列表

转载 作者:行者123 更新时间:2023-12-05 02:32:46 26 4
gpt4 key购买 nike

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

def sample_def(var:list[str]):

最佳答案

我会使用typing模块

from typing import List

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

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

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

from collections.abc import Iterable

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

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

关于python - 类型提示字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71148612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com