Delete circular links in dicts, lists, tuples

I have the following code for hacking that removes circular references from any data structure built from objects dict, tupleand list.

import ast

def remove_circular_refs(o):
    return ast.literal_eval(str(o).replace("{...}", 'None'))

But I don't like how much hacks it is. Can this be done without turning the data structure into a string representation?

Here is an example structure for validation:

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)
+4
source share
1 answer

Do not use string conversion, no. Just define the link by moving the data structure:

def remove_circular_refs(ob, _seen=None):
    if _seen is None:
        _seen = set()
    if id(ob) in _seen:
        # circular reference, remove it.
        return None
    _seen.add(id(ob))
    res = ob
    if isinstance(ob, dict):
        res = {
            remove_circular_refs(k, _seen): remove_circular_refs(v, _seen)
            for k, v in ob.items()}
    elif isinstance(ob, (list, tuple, set, frozenset)):
        res = type(ob)(remove_circular_refs(v, _seen) for v in ob)
    # remove id again; only *nested* references count
    _seen.remove(id(ob))
    return res

dict, list, tuple, set frozenset; memoises id() , , None.

:

>>> doc1 = {
...     "key": "value",
...     "type": "test1",
... }
>>> doc1["self"] = doc1
>>> doc1
{'key': 'value', 'type': 'test1', 'self': {...}}
>>> remove_circular_refs(doc1)
{'key': 'value', 'type': 'test1', 'self': None}
>>> doc2 = {
...     'foo': [],
... }
>>> doc2['foo'].append((doc2,))
>>> doc2
{'foo': [({...},)]}
>>> remove_circular_refs(doc2)
{'foo': [(None,)]}
>>> doc3 = {
...     'foo': 'string 1', 'bar': 'string 1',
...     'ham': 1, 'spam': 1
... }
>>> remove_circular_refs(doc3)
{'foo': 'string 1', 'bar': 'string 1', 'ham': 1, 'spam': 1}

doc3 ; 'string 1' 1 , , .

+6

Source: https://habr.com/ru/post/1680191/


All Articles