Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Endless recursion vs while True? [closed]

I am writing code and right now what I am going to be doing (simple version) is always have my function running gathering data and parsing it then making decisions then output those decisions to the screen and rerunning it directly after I just had an idea to use endless recursion like below:

funcone():
    #do a bunch of calculations that add to an output list
    startnewoutputthread(output_list) #outputs stuff to the screen
    startnewfunconethread(funcone)

funcone()

instead current code which wraps everything in funcone() with a while True: statement in a thread with the outputting at the end in a new thread.

Would one be better than the other? I do not think endless recursion would be bad because the threads that are starting are all going to be finishing after new ones are started?

like image 285
Jay Bell Avatar asked Apr 10 '26 15:04

Jay Bell


2 Answers

Don't do endless recursion. It will use far more memory than your while True: loop, and if the program runs long enough, you'll exceed the maximum recursion depth (which defaults to 1000) and get a RuntimeError.

like image 195
dano Avatar answered Apr 13 '26 03:04

dano


TL;DR: The CPython interpreter doesn't implement tail recursion elimination, so use iteration

IF you are using the CPYthon interpreter then you have a problem because it doesn't implement tail recursion elimination. This means at some point you will get a stack overflow as the new stack frames pile up. In this case it's better to use iteration.

That being said someone did create a decorator to implement tail recursion.

All that being said it's better to use iteration in Python as that would be the most idiomatic implementation ie. "Pythonic".

like image 21
dietbuddha Avatar answered Apr 13 '26 03:04

dietbuddha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!