Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8901661
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T01:24:55+00:00 2026-06-15T01:24:55+00:00

BACKGROUND When playing around, I often write simple recursive functions looking something like: def

  • 0

BACKGROUND

When playing around, I often write simple recursive functions looking something like:

def f(a,b):
    if a>=0 and b>=0:
        return min( f(a-1,b) , f(b,a-1) ) # + some cost that depends on a,b
    else:
        return 0

(For example, when computing weighted edit distances, or evaluating recursively defined mathematical formulas.)

I then use a memoizing decorator to cache the results automatically.

PROBLEM

When I try something like f(200,10) I get:

RuntimeError: maximum recursion depth exceeded

This is as expected because the recursive implementation exhausts Python’s stack space/ recursion limits.

WORKAROUNDS

I usually work around this problem by one of:

  • Increasing recursion limit with sys.setrecursionlimit (only works up to about 1000 depth)
  • Using a for loop to fill up the cache for smaller values
  • Changing the function to use a list as a manual stack (via append and pop calls) (in other words, moving from a recursive implementation to an iterative one)
  • Using an alternative programming language

but I find all of these quite error prone.

QUESTION

Is there a way to write an @Bigstack decorator that would simulate the effect of having a really big stack?

Note that my functions normally make several recursive function calls so this is not the same as tail recursion – I really do want to save all the internal state of each function on the stack.

WHAT I’VE TRIED

I’ve been thinking about using a list of generator expressions as my stack. By probing the stackframe I could work out when the function has been called recursively and then trigger an exception to return to the decorator code. However, I can’t work out a way of gluing these ideas together to make anything that actually works.

Alternatively, I could try accessing the abstract syntax tree for the function and try transforming calls to recursive functions to yield statements, but this seems like it’s heading in the wrong direction.

Any suggestions?

EDIT

It certainly looks like I am misusing Python, but another approach I have been considering is to use a different thread for each block of, say, 500 stack frames and then insert queues between each consecutive pair of threads – one queue for arguments, and another queue for return values. (Each queue will have at most one entry in it.) I think this probably doesn’t work for some reason – but I’ll probably only work out why after I’ve tried to implement it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T01:24:56+00:00Added an answer on June 15, 2026 at 1:24 am

    To get around the recursion limit, you can catch the RuntimeError exception to detect when you’ve run out of stack space, and then return a continuation-ish function that, when called, restarts the recursion at the level where you ran out of space. Call this (and its return value, and so on) until you get a value, then try again from the top. Once you’ve memoized the lower levels, the higher levels won’t run into a recursion limit, so eventually this will work. Put the repeated-calling-until-it-works in a wrapper function. Basically it’s a lazy version of your warming-up-the-cache idea.

    Here’s an example with a simple recursive “add numbers from 1 to n inclusive” function.

    import functools
    
    def memoize(func):
        cache = {}
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            key = args, tuple(sorted(kwargs.items()))
            if key in cache:
                return cache[key]
            else:
                result = func(*args, **kwargs)
                if not callable(result):
                    cache[key] = result
                return result
        return wrapper
    
    @memoize
    def _addup(n):
        if n < 2:
            return n
        else:
            try:
                result = _addup(n - 1)
            except RuntimeError:
                return lambda: _addup(n)
            else:
                return result if callable(result) else result + n
    
    def addup(n):
        result = _addup(n)
        while callable(result):
            while callable(result):
                result = result()
            result = _addup(n)
        return result
    
    assert addup(5000) == sum(xrange(5001))
    

    Rather than returning the lambda function all the way back up the call chain, we can raise an exception to short-circuit that, which both improves performance and simplifies the code:

    # memoize function as above, or you can probably use functools.lru_cache
    
    class UnwindStack(Exception):
        pass
    
    @memoize
    def _addup(n):
        if n < 2:
            return n
        else:
            try:
                return _addup(n - 1) + n
            except RuntimeError:
                raise UnwindStack(lambda: _addup(n))
    
    def _try(func, *args, **kwargs):
        try:
            return func(*args, **kwargs)
        except UnwindStack as e:
            return e[0]
    
    def addup(n):
        result = _try(_addup, n)
        while callable(result):
            while callable(result):
                result = _try(result)
            result = _try(_addup, n)
        return result
    

    This remains pretty inelegant, though, and still has a fair amount of overhead, and I can’t imagine how you’d make a decorator out it. Python isn’t really suited to this kind of thing, I guess.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm just learning c++ coming from a Java background. Just playing around with simple
just a simple question i am stuck with. i am playing around with some
I'm playing around with visual controls and colors in a simple background color changing
Background I'm playing around with a FIFO and every time I try to write
Quick background I'm a Java developer who's been playing around with C++ in my
I'm playing around with the iosched app from Google I/O 2011. Looking at the
I was playing around with some chrome extensions and I found this example: http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/pageAction/pageaction_by_url/
I've been playing around with Android development and one of the things I'd like
I've been playing around storing tweets inside mongodb, each object looks like this: {
A little background - I am playing around with pygame, and want to create

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.