Search code examples
pythonrecursion

Test when recursion limit is reached in python


Is there a way to test when a program's recursion limit is reached? For example:

def funct():
    print "Hello"
    #Some code for testing the recursion limit.
        #Some more code to execute

If you are wondering why I want to know this, here is why: I want to hide an Easter egg in a program, but I can't do that until I found out how to do what I am asking. So, how can I test when the recursion limit is reached? Is there even a way?


Solution

  • You can test for the RuntimeError like any other error, with try:

    def funct():
        ...
        try:
           funct()
        except RuntimeError as e:
            if "recursion" in e.message:
                print("Easter egg!")
    

    Note that I've added an extra check that the error is warning about recursion, so you don't prevent any other RuntimeErrors from going about their business.