python - 如何在 Python 中输入提示某种数据类型的(任意)集合?

标签 python python-3.x type-hinting

如果我有一个类似的函数:

def some_function(paths):
    for path in paths:
        other_function(path)

输入提示路径的正确方法是什么?该函数的目的是 paths 中的每个对象都是一个字符串,但显然 paths 可以是列表、元组、集合、numpy 数组、pandas 系列等,因此以下似乎太具体:

def some_function(paths: list[str]):
    for path in paths:
        other_function(path)

我应该使用 typing 模块中的 CollectionSequence 吗?

最佳答案

由于您在这里唯一依赖的是可迭代性,所以要求它。

from typing import Iterable

def some_function(paths: Iterable[str]):
    for path in paths:
        other_function(path)

如果这些确实应该是文件系统路径,您可以调整它以允许 str 或任何支持 os.PathLike ABC 的内容。 :

import os
from typing import Iterable

def some_function(paths: Iterable[str | os.PathLike]):  # On older Python, Iterable[Union[str, os.PathLike]]
    for path in paths:
        other_function(path)

关于python - 如何在 Python 中输入提示某种数据类型的(任意)集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73030337/

相关文章:

python - 如何在 for 循环中注释类型?

python - 如何将初始隐藏状态传递给lstm层?

python - 将数据帧拆分为子数据帧并与一行重新组合以表示数据帧

list - 如何在包含重复项的排序列表的非连续 float 元素之间填充零?

python - python 类的类型提示

python - 返回图像的函数的类型提示是什么?

python - Celery: '|' 运算符在链接多任务时如何工作?

python - Pandas :选择仅包含字符串的行?

Python字符串插值实现

python - 在 NLP 中提取包括连字符在内的复合名词时遇到问题