不使用库,您还可以定义一个简单的递归函数,如下所示:
def check_structure(struct, conf): if isinstance(struct, dict) and isinstance(conf, dict): # struct is a dict of types or other dicts return all(k in conf and check_structure(struct[k], conf[k]) for k in struct) if isinstance(struct, list) and isinstance(conf, list): # struct is list in the form [type or dict] return all(check_structure(struct[0], c) for c in conf) elif isinstance(struct, type): # struct is the type of conf return isinstance(conf, struct) else: # struct is neither a dict, nor list, not type return False
假设配置可以包含不在您的结构中的键,如您的示例。
更新:新版本还支持列表,例如
'foo': [{'bar': int}]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)