Cheat against recursion limit - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Cheat against recursion limit (/thread-16003.html) |
Cheat against recursion limit - DeaD_EyE - Feb-10-2019 My question was: Is it possible to bypass the recursion limit with generators and yield from? Answer: You can prevent the RecursionError , but you are still limited in recursion.Here a function to generate a nested list: def construct_deep_list(n): x = y = [] for _ in range(n): x.append([]) x = x[0] x.append('Secret') return y construct_deep_list(10) Now getting the recursionlimit, generating the deep_list and printing it to console.import sys deep_list = construct_deep_list(sys.getrecursionlimit()) print(deep_list)Then you get this error: Now a normal function to traverse the deep list. str and bytes are not allowed to prevent morecomplicated code. def test_recursion(iterable): try: iterator = iter(iterable) except TypeError: return iterable else: while True: try: element = next(iterator) if isinstance(element, (str, bytes)): raise ValueError('str or bytes are not allowed') return test_recursion(element) except StopIteration: breakTesting the functions: result = test_recursion([[True]]) print(result)It works: Now let's try it with the deep_list:result2 = test_recursion(deep_list) The deep_list has one str inside. But we got the RecursionError and not the ValueError.This means, the interpreter was not able to get finally the str element. The recursion limit was hit before. Now let's try it with the generator version: def deep_iter(iterable): for element in iterable: try: yield from deep_iter(element) except: yield element result3 = list(deep_iter(deep_list)) print(result3) Conclusion: Generators can simplify your code. But I still do not know why the yield from does not hit the recursion limit.I guess the recursion limit is still thrown, but goes in silence away. Apply the generator twice gives: result4 = list(deep_iter(deep_iter(deep_list))) print(result4) Extended generator, which does not iterate over str and bytes :def deep_iter2(iterable, ignore=(str, bytes)): for element in iterable: if isinstance(element, ignore): yield element continue try: yield from deep_iter2(element) except: yield element print(list(deep_iter2(deep_iter2(deep_list)))) I'm not sure if it's usable in production code. But usually you should not have deep nested data structures in production code (hopefully).Instead of using yield from , I use the deque in the final version.This also faster. from collections import deque def deep_iter3(iterable, ignore=(str, bytes)): heap = deque([iterable]) while heap: element = heap.popleft() if isinstance(element, ignore): yield element continue try: sub_heap = [] for sub_element in element: sub_heap.append(sub_element) except TypeError: yield element else: heap.extendleft(reversed(sub_heap)) list(deep_iter3([1,2, ['test'], (3,1),4, deep_list])) Some benchmarks:
RE: Cheat against recursion limit - perfringo - Feb-10-2019 On topic of Python recursion: A thing I learned about Python recursion Quote:In Python 3, all comprehensions (and in Python 2 all except list comprehensions) are actually compiled as nested functions. Executing the generator comprehension calls that hidden nested function, using up an extra stack frame. RE: Cheat against recursion limit - DeaD_EyE - Feb-10-2019 Interesting article. I like the pragmatic talks from Ned Batchelder. I added a comment to the article with a link to this thread. |