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 8353491
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T09:16:39+00:00 2026-06-09T09:16:39+00:00

The following function is meant to be used as a decorator that stores the

  • 0

The following function is meant to be used as a decorator that stores the results of already computed values. If the argument has already been calculated before, the function will return the value stored in the cache dictionary:

def cached(f):
    f.cache = {}
    def _cachedf(*args):
        if args not in f.cache:
            f.cache[args] = f(*args)

        return f.cache[args]

    return _cachedf

I realized (by mistake) that cache does not need to be an attribute of the function object. As a matter of facts, the following code works as well:

def cached(f):
    cache = {}   # <---- not an attribute this time!
    def _cachedf(*args):
        if args not in cache:
            cache[args] = f(*args)

        return cache[args]
    return _cachedf

I am having a hard time understanding how can the cache object be persistent across multiple calls. I tried calling multiple cached functions several times and could not find any conflict or problems.

Can anyone please help me understand how the cache variable still exists even after the _cachedf function is returned?

  • 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-09T09:16:41+00:00Added an answer on June 9, 2026 at 9:16 am

    You are creating a closure here: The function _cachedf() closes over the variable cache from the enclosing scope. This keeps cache alive as long as the function object lives.

    Edit: Maybe I should add a few more details on how this works in Python and how CPython implements this.

    Let’s look at a simpler example:

    def f():
        a = []
        def g():
            a.append(1)
            return len(a)
        return g
    

    Example usage in the interactive interpreter

    >>> h = f()
    >>> h()
    1
    >>> h()
    2
    >>> h()
    3
    

    During compilation of the module containing the function f(), the
    compiler sees that the function g() references the name a from the
    enclosing scope and memorises this external reference in the code
    object corresponding to the function f() (specifically, it adds the
    name a to f.__code__.co_cellvars).

    So what happens when the function f() is called? The first line
    create a new list object and binds it to the name a. The next line
    creates a new function object (using a the code object created during
    the compilation of the module) and binds it to the name g. The body
    of g() isn’t executed at this point, and finally the funciton object
    is returned.

    Since the code object of f() has a note that the name a is
    referenced by local functions, a “cell” for this name is created when
    f() is entered. This cell contains the reference to the actual list
    object a is bound to, and the function g() gets a reference to
    this cell. That way, the list object and the cell are kept alive even
    when the funciton f() exits.

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

Sidebar

Related Questions

The following function rewrites urls from news and product titles that contain all sorts
The following function that reports the current line-number (and time) which I would like
i was following an ACL tut. which has used this piece of code. class
//Following function add new table entry to table //and return interface which has function
I've been working on some C++ code that a friend has written and I
I need to parse JSON in jQuery autocomplete function. I used following code. jQuery(#name).autocomplete(
What delay-load dependencies\functions are meant for in the following document? http://www.dependencywalker.com/faq.html Thanks
Possible Duplicate: What do parentheses surrounding a JavaScript object/function/class declaration mean? Why following code
I use the following call to openCV function to perform K-means algorithm: cvKMeans2(points, count,
The following function is designed to check whether this row in this tables exists.

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.