Python风格递归检查字段非空的优雅实现及字典场景适配
Python风格的嵌套字段非空检查方案
类实例场景
你原来的长串判断可以用Python的**EAFP(请求原谅比请求许可更容易)**原则简化,直接尝试访问最深层字段,捕获中间环节可能抛出的AttributeError:
try: if team.captain.address.zipcode is not None: do_something() except AttributeError: pass
如果需要复用这种嵌套属性获取逻辑,可借助functools.reduce封装通用函数实现链式属性访问:
from functools import reduce def get_nested_attr(obj, attr_chain, default=None): try: return reduce(getattr, attr_chain, obj) except AttributeError: return default # 使用示例 if get_nested_attr(team, ["captain", "address", "zipcode"]) is not None: do_something()
字典场景
对于嵌套字典,逻辑类似,但需捕获KeyError(键不存在)和TypeError(对象为None/非字典):
try: if team["captain"]["address"]["zipcode"] is not None: do_something() except (KeyError, TypeError): pass
同样可封装通用函数处理字典的嵌套键访问:
from functools import reduce def get_nested_dict(dct, key_chain, default=None): try: return reduce(lambda current, key: current[key], key_chain, dct) except (KeyError, TypeError): return default # 使用示例 if get_nested_dict(team, ["captain", "address", "zipcode"]) is not None: do_something()
注意:若尝试用team.get('captain', {}).get('address', {}).get('zipcode')这种链式get写法,需确保中间每一层默认值为字典——如果某个节点是None而非字典,该写法会抛出AttributeError,因此try-except或通用函数的方式更稳妥。
内容的提问来源于stack exchange,提问作者Daniele Repici
相关产品推荐
相关产品推荐

