Skip to content

Latest commit

 

History

History
54 lines (43 loc) · 2.15 KB

ReadMe.md

File metadata and controls

54 lines (43 loc) · 2.15 KB

RecursionSafe.py Unlicensed work

wheel (GitLab) wheel (GHA via nightly.link) GitLab Build Status GitLab Coverage GitHub Actions N∅ hard dependencies Libraries.io Status Code style: antiflash

A context manager to protect you from infinite recursion when walking collections.

Just wrap a recursive function with it. If you visit any object you are already in you will get ellipsis instead of the object, be ready for it.

Example

recSafe = RecursionSafe()

objs = {
	"a": {},
	"a.b": {},
	"a.b.c": {},
	"a.b.d": {},
	"a.b.c.d": 14,
	"a.e": 10,
	"a.f": {},
}

objs["a"]["b"] = objs["a.b"]
objs["a.b"]["c"] = objs["a"]
objs["a.b"]["d"] = objs["a.b.d"]
objs["a.b.c"]["d"] = objs["a.b.c.d"]
objs["a"]["e"] = objs["a.e"]
objs["a"]["f"] = objs["a.f"]
objs["a.f"]["g"] = objs["a"]
a = objs["a"]

idsToNames = {id(objs[k]): k for k in objs}


@recSafe.wrap
def ownRepr(a):
	if isinstance(a, dict):
		return "{" + ", ".join((ownRepr(k) + ":" + ownRepr(v) for k, v in a.items())) + "}"
	else:
		return repr(a)


print("repr", repr(a))  # even non-recursive objects are ellipsed
print("ownRepr", ownRepr(a))  # feel the difference - non-self-referencing objects are not ellipsed