infinitely recursive data structures

I learned recently that you can use a Python built in to elegantly print recursive data structures.

from reprlib import recursive_repr

class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next

def __repr__(self):
return f"Node({self.value}, {self.next})"


class InfNode:
def __init__(self, value, next=None):
self.value = value
self.next = next

@recursive_repr()
def __repr__(self):
return f"Node({self.value}, {self.next})"

if __name__ == "__main__":
root = InfNode(1)
root.next = InfNode(2, root)
print(root)

root = Node(1)
root.next = Node(2, root)
print(root)

Generally when you try to print something like a linked list that refers to itself, you will get the following error. This means that Python tries to traverse and hits the max recursion limit at which point it exits without printing.

Traceback (most recent call last):
File "/Users/inf_rec.py", line 28, in <module>
print(root)
File "/Users/inf_rec.py", line 9, in __repr__
return f"Node({self.value}, {self.next})"
File "/Users/inf_rec.py", line 9, in __repr__
return f"Node({self.value}, {self.next})"
File "/Users/inf_rec.py", line 9, in __repr__
return f"Node({self.value}, {self.next})"
[Previous line repeated 330 more times]
RecursionError: maximum recursion depth exceeded while getting the str of an object

With the @recursive_repr decorator, the code detects that recursion happens and formats it nicely.

Node(1, Node(2, ...))