如何为返回不同类型值的Python函数正确编写类型注解
你写的int or str不属于合法的Python类型注解语法,同时函数返回值注解前遗漏了必填的->标记,类型检查工具无法识别这类写法。针对函数返回多种不同类型值的场景,需要使用*联合类型(Union Type)*编写注解,不同Python版本对应的写法存在差异:
不同Python版本的正确注解写法
Python 3.10 及以上版本
直接使用内置的|运算符拼接所有可能的返回类型即可,是目前官方推荐的最简写法:def findElement(values: tuple, toFind) -> int | str: """Search for a value in the tuple and returns it index value.""" for value in values: if value == toFind: return values.index(value) return "Requested value not found in the tuple.."Python 3.5 ~ 3.9 版本
需要先从标准库typing模块导入Union工具,再把所有可能的返回类型作为参数传入:from typing import Union def findElement(values: tuple, toFind) -> Union[int, str]: """Search for a value in the tuple and returns it index value.""" for value in values: if value == toFind: return values.index(value) return "Requested value not found in the tuple.."
更优的工程实践建议
你当前通过返回字符串表示查找失败的写法存在隐患:调用方很容易忽略字符串分支,直接将返回值作为索引使用触发运行时错误。更推荐两种改造方案:
- 查找失败时抛出明确异常(如
ValueError),此时函数返回类型固定为int,逻辑更清晰,不需要处理多返回类型的问题 - 不抛异常的场景下,用
None代替错误字符串作为查找失败的返回值,对应类型注解为int | None(3.10+)或Optional[int](低版本),类型检查工具可以自动提示调用方做判空处理,减少漏判bug:def findElement(values: tuple, toFind) -> int | None: """Search for a value in the tuple and returns it index value.""" for value in values: if value == toFind: return values.index(value) return None
内容的提问来源于stack exchange,提问作者user19547510
相关产品推荐
相关产品推荐

