本文介绍了在 python 中判断可能为 none 的输入是否为空容器(如列表、元组等)的惯用写法,避免滥用异常处理,提升代码可读性与健壮性。
在 Python 开发中,函数参数常被设计为可选(默认值为 None),且该参数预期为某种支持 len() 的容器类型(如 list、tuple、str、set 等)。此时,若需区分三种状态——None、非空容器、空容器(如 [] 或 ()),应避免依赖 try/except 捕获 TypeError(因 len(None) 报错)和 AssertionError(用于逻辑判断)来统一处理。这种写法虽能运行,但违背了“EAFP(Easier to Ask for Forgivenes
s than Permission)”原则的合理边界:异常应处理真正意外的情况,而非常规控制流。
更符合 Python 惯用法(idiomatic)的方式是显式、清晰地进行逻辑判断:
def func(ids=None):
if ids is not None and not ids:
return {}
# do some stuff and return {}✅ 说明:
⚠️ 注意事项:
if ids is None:
# handle missing input
elif not ids:
# handle empty container
return {}
else:
# handle non-empty container总结:用 if ids is not None and not ids: 替代 try/except 处理 None 和空容器,语义清晰、性能更优、符合 Python 哲学,是推荐的惯用写法。