Python 为不是 str 的 Iterable[str] 键入提示
Python type hint for Iterable[str] that isn't str
在Python中,有没有办法区分字符串和字符串的其他迭代?
A str
作为 Iterable[str]
类型有效,但这可能不是函数的正确输入。例如,在这个旨在对文件名序列进行操作的简单示例中:
from typing import Iterable
def operate_on_files(file_paths: Iterable[str]) -> None:
for path in file_paths:
...
传入单个文件名会产生错误结果,但不会被类型检查发现。我知道我可以在运行时检查字符串或字节类型,但我想知道是否可以使用类型检查工具来捕捉像这样的愚蠢错误。
我查看了 collections.abc
模块,似乎没有任何 abc 包含典型的可迭代对象(例如列表、元组)但不包含字符串。同样,对于 typing
模块,似乎没有不包含字符串的可迭代类型。
截至 2022 年 3 月,答案是 否。
这个问题至少从 2016 年 7 月就开始讨论了。关于区分 str
和 Iterable[str]
的提案,Guido van Rossum 写道:
Since str
is a valid iterable of str
this is tricky. Various proposals have been made but they don't fit easily in the type system.
您需要列出您希望函数显式接受的所有类型,使用 Union
(3.10 之前的版本)或 |
(3.10 及更高版本)。
例如对于 3.10 之前的版本,使用:
from typing import Union
## Heading ##
def operate_on_files(file_paths: Union[TypeOneName, TypeTwoName, etc.]) -> None:
for path in file_paths:
...
对于 3.10 及更高版本,使用:
## Heading ##
def operate_on_files(file_paths: TypeOneName | TypeTwoName | etc.) -> None:
for path in file_paths:
...
如果你恰好在使用 Pytype,it will not treat str
as an Iterable[str]
(as pointed out by Kelly Bundy)。但是,这种行为是 typechecker-specific,并没有在其他类型检查器中得到广泛支持。
在Python中,有没有办法区分字符串和字符串的其他迭代?
A str
作为 Iterable[str]
类型有效,但这可能不是函数的正确输入。例如,在这个旨在对文件名序列进行操作的简单示例中:
from typing import Iterable
def operate_on_files(file_paths: Iterable[str]) -> None:
for path in file_paths:
...
传入单个文件名会产生错误结果,但不会被类型检查发现。我知道我可以在运行时检查字符串或字节类型,但我想知道是否可以使用类型检查工具来捕捉像这样的愚蠢错误。
我查看了 collections.abc
模块,似乎没有任何 abc 包含典型的可迭代对象(例如列表、元组)但不包含字符串。同样,对于 typing
模块,似乎没有不包含字符串的可迭代类型。
截至 2022 年 3 月,答案是 否。
这个问题至少从 2016 年 7 月就开始讨论了。关于区分 str
和 Iterable[str]
的提案,Guido van Rossum 写道:
Since
str
is a valid iterable ofstr
this is tricky. Various proposals have been made but they don't fit easily in the type system.
您需要列出您希望函数显式接受的所有类型,使用 Union
(3.10 之前的版本)或 |
(3.10 及更高版本)。
例如对于 3.10 之前的版本,使用:
from typing import Union
## Heading ##
def operate_on_files(file_paths: Union[TypeOneName, TypeTwoName, etc.]) -> None:
for path in file_paths:
...
对于 3.10 及更高版本,使用:
## Heading ##
def operate_on_files(file_paths: TypeOneName | TypeTwoName | etc.) -> None:
for path in file_paths:
...
如果你恰好在使用 Pytype,it will not treat str
as an Iterable[str]
(as pointed out by Kelly Bundy)。但是,这种行为是 typechecker-specific,并没有在其他类型检查器中得到广泛支持。