|
| 1 | +RecursionSafe.py [](https://unlicense.org/) |
| 2 | +================================ |
| 3 | +~~[wheel (GitLab)](https://gitlab.com/KOLANICH/RecursionSafe.py/-/jobs/artifacts/master/raw/dist/RecursionSafe-0.CI-py3-none-any.whl?job=build)~~ |
| 4 | +~~[wheel (GHA via `nightly.link`)](https://nightly.link/KOLANICH-libs/RecursionSafe.py/workflows/CI/master/RecursionSafe-0.CI-py3-none-any.whl)~~ |
| 5 | +~~~~ |
| 6 | +~~~~ |
| 7 | +~~[](https://github.com/KOLANICH-libs/RecursionSafe.py/actions/)~~ |
| 8 | + |
| 9 | +[](https://libraries.io/github/KOLANICH-libs/RecursionSafe.py) |
| 10 | +[](https://codeberg.org/KOLANICH-tools/antiflash.py) |
| 11 | + |
| 12 | +A context manager to protect you from infinite recursion when walking collections. |
| 13 | + |
| 14 | +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. |
| 15 | + |
| 16 | +Example |
| 17 | +------- |
| 18 | +```python |
| 19 | +recSafe = RecursionSafe() |
| 20 | + |
| 21 | +objs = { |
| 22 | + "a": {}, |
| 23 | + "a.b": {}, |
| 24 | + "a.b.c": {}, |
| 25 | + "a.b.d": {}, |
| 26 | + "a.b.c.d": 14, |
| 27 | + "a.e": 10, |
| 28 | + "a.f": {}, |
| 29 | +} |
| 30 | + |
| 31 | +objs["a"]["b"] = objs["a.b"] |
| 32 | +objs["a.b"]["c"] = objs["a"] |
| 33 | +objs["a.b"]["d"] = objs["a.b.d"] |
| 34 | +objs["a.b.c"]["d"] = objs["a.b.c.d"] |
| 35 | +objs["a"]["e"] = objs["a.e"] |
| 36 | +objs["a"]["f"] = objs["a.f"] |
| 37 | +objs["a.f"]["g"] = objs["a"] |
| 38 | +a = objs["a"] |
| 39 | + |
| 40 | +idsToNames = {id(objs[k]): k for k in objs} |
| 41 | + |
| 42 | + |
| 43 | +@recSafe.wrap |
| 44 | +def ownRepr(a): |
| 45 | + if isinstance(a, dict): |
| 46 | + return "{" + ", ".join((ownRepr(k) + ":" + ownRepr(v) for k, v in a.items())) + "}" |
| 47 | + else: |
| 48 | + return repr(a) |
| 49 | + |
| 50 | + |
| 51 | +print("repr", repr(a)) # even non-recursive objects are ellipsed |
| 52 | +print("ownRepr", ownRepr(a)) # feel the difference - non-self-referencing objects are not ellipsed |
| 53 | +``` |
| 54 | + |
0 commit comments