如果我有一个类似的函数:
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
模块中的 Collection
或 Sequence
吗?
最佳答案
由于您在这里唯一依赖的是可迭代性,所以要求它。
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/