G
G
Geek2282020-08-25 00:48:02
Python
Geek228, 2020-08-25 00:48:02

python 3 recursion interrupt?

Is it possible to somehow interrupt or stop, reset, cut off, cut off, at least lengthen, make it infinite, or disable, recursion in python without return (it does not help in my script), can sys or os fix this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2020-08-25
@shurshur

You can make your own exception, raise this exception in the right place and catch it outside.

import random

class StopRecursion(Exception):
  pass

def some_recursive_function(depth=0):
  print ("depth=%d" % depth)
  # играем в русскую рулетку
  if random.randint(1,6) == 4:
    raise StopRecursion
  some_recursive_function(depth+1)

try:
  some_recursive_function()
except StopRecursion:
  print ("Recursion stopped")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question