如何用Python内置方法实现更Pythonic的函数入参int/str校验?
嘿,先揪出原代码里的隐形bug
你的if type(input_argument) is not int or type(input_argument) is not str判断逻辑有问题——任何输入都会触发这个条件(毕竟一个变量不可能同时是int和str),所以哪怕传个合法的int进去,函数也会直接返回None,这显然不是你想要的效果~
更Pythonic的简化写法
我们可以利用Python的isinstance()(比直接用type()更适配继承场景)、特定异常捕获、f-string等特性来简化,同时严格排除bool类型(因为bool是int的子类,isinstance(True, int)会返回True,必须单独处理):
def foo(input_argument): func_name = "foo" # 先排除bool,再校验是否是int/str类型 if isinstance(input_argument, bool) or not isinstance(input_argument, (int, str)): print(f"{func_name}: 'input_argument' expects int/str, not {type(input_argument).__name__}") return None try: # int类型转换后还是自身,str则尝试转成int converted_input = int(input_argument) except ValueError: # 只捕获str无法转int的情况,避免裸except捕获无关异常 print(f"{func_name}: 'input_argument' expects number in str/int format") return None # 这里可以添加函数的核心业务逻辑 return converted_input
再进一步:把校验和异常处理合并(更紧凑)
如果想要更简洁,还可以把类型校验和转换逻辑合并,利用int()抛出的不同异常来区分类型错误和格式错误:
from typing import Union, Optional # 加上类型提示,让函数意图更清晰(Python3.5+支持) def foo(input_argument: Union[int, str]) -> Optional[int]: func_name = "foo" # 单独排除bool,避免True/False被当成int通过 if isinstance(input_argument, bool): print(f"{func_name}: 'input_argument' expects int/str, not bool") return None try: return int(input_argument) except TypeError: # 输入不是int/str时,int()会抛出TypeError print(f"{func_name}: 'input_argument' expects int/str, not {type(input_argument).__name__}") return None except ValueError: # 是str但无法转成合法int时抛出ValueError print(f"{func_name}: 'input_argument' expects number in str/int format") return None
关键优化点说明
- 用
isinstance()替代type() is:更符合Python的类型判断习惯,同时能处理继承场景(但因为bool是int的子类,所以必须提前排除) - 捕获特定异常而非裸
except:避免意外捕获KeyboardInterrupt等无关异常,代码更健壮 - 用f-string格式化输出:比老的
%写法更易读、更简洁 - 用
type(input_argument).__name__:打印的类型名更友好(比如显示bool而非<class 'bool'>) - 可选的类型提示:让函数的入参和返回值类型更清晰,便于维护
内容的提问来源于stack exchange,提问作者Sir DrinksCoffeeALot
相关产品推荐
相关产品推荐

