我有这个真的如下破解代码将删除任何类型的数据结构的建造出来的循环引用dict,tuple和list对象.
import ast
def remove_circular_refs(o):
return ast.literal_eval(str(o).replace("{...}", 'None'))
Run Code Online (Sandbox Code Playgroud)
但我不喜欢它有多酷.这可以在不将数据结构转换为字符串表示的情况下完成吗?
这是一个用于测试的示例结构:
doc1 = {
"key": "value",
"type": "test1",
}
doc1["self"] = doc1
doc = {
'tags': 'Stackoverflow python question',
'type': 'Stackoverflow python question',
}
doc2 = {
'value': 2,
'id': 2,
}
remove_circular_refs(doc)
remove_circular_refs(doc1)
remove_circular_refs(doc2)
Run Code Online (Sandbox Code Playgroud)