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

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

嵌套字典在设置项目时充当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']
。一个更完整的解决方案将需要实际分析代码行以找出变量在赋值中的位置。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5654874.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存