栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

嵌套字典在设置项目时充当defaultdict,但在获取项目时不充当

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

嵌套字典在设置项目时充当defaultdict,但在获取项目时不充当

不可能。

test_dict['level_1']['level_2']['level_3'] = 'Hello'

在语义上等效于:

temp1 = test_dict['level_1'] # Should this line fail?temp1['level_2']['level_3'] = 'Hello'

但是…如果确定要实现它,则可以检查Python堆栈以获取/解析代码调用行,然后根据代码调用行是否包含分配来改变行为!不幸的是,有时调用代码在堆栈跟踪中不可用(例如,以交互方式调用时),在这种情况下,您需要使用Python字节码。

import disimport inspectfrom collections import UserDictdef get_oppres(pre_object, lineno):    """Utility function to extract Python VM oppres for line of pre"""    line_ops = []    instructions = dis.get_instructions(pre_object).__iter__()    for instruction in instructions:        if instruction.starts_line == lineno: # found start of our line line_ops.append(instruction.oppre) break    for instruction in instructions:        if not instruction.starts_line: line_ops.append(instruction.oppre)        else: # start of next line break    return line_opsclass TestDict(UserDict):    def __getitem__(self, key):        try: return super().__getitem__(key)        except KeyError: # inspect the stack to get calling line of pre frame = inspect.stack()[1].frame oppres = get_oppres(frame.f_pre, frame.f_lineno) # STORE_SUBSCR is Python oppre for TOS1[TOS] = TOS2 if dis.opmap['STORE_SUBSCR'] in oppres:     # calling line of pre contains a dict/array assignment     default = TestDict()     super().__setitem__(key, default)     return default else:     raisetest_dict = TestDict()test_dict['level_1']['level_2']['level_3'] = 'Hello'print(test_dict)# {'level_1': {'level_2': {'level_3': 'Hello'}}}test_dict['unknown_key']# KeyError: 'unknown_key'

以上只是部分解决方案。如果同一行上还有其他字典/数组分配,仍然可以上当,例如

other['key'] =test_dict['unknown_key']
。一个更完整的解决方案将需要实际分析代码行以找出变量在赋值中的位置。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652747.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号