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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T18:25:13+00:00 2026-05-15T18:25:13+00:00

I want to create a decorator that works like a property, only it calls

  • 0

I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example:

def SomeClass(object):
    @LazilyInitializedProperty
    def foo(self):
        print "Now initializing"
        return 5

>>> x = SomeClass()
>>> x.foo
Now initializing
5
>>> x.foo
5

My idea was to write a custom decorator for this. So i started, and this is how far I came:

class LazilyInitializedProperty(object):
    def __init__(self, function):
        self._function = function

    def __set__(self, obj, value):
        raise AttributeError("This property is read-only")

    def __get__(self, obj, type):
        # problem: where to store the value once we have calculated it?

As you can see, I do not know where to store the cached value. The simplest solution seems to be to just maintain a dictionary, but I am wondering if there is a more elegant solution for this.

EDIT Sorry for that, I forgot to mention that I want the property to be read-only.

  • 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-05-15T18:25:14+00:00Added an answer on May 15, 2026 at 6:25 pm

    Denis Otkidach’s CachedAttribute is a method decorator which makes attributes lazy (computed once, accessible many). To make it also read-only, I added a __set__ method. To retain the ability to recalculate (see below) I added a __delete__ method:

    class ReadOnlyCachedAttribute(object):    
        '''Computes attribute value and caches it in the instance.
        Source: Python Cookbook 
        Author: Denis Otkidach https://stackoverflow.com/users/168352/denis-otkidach
        This decorator allows you to create a property which can be computed once and
        accessed many times. Sort of like memoization
        '''
        def __init__(self, method, name=None):
            self.method = method
            self.name = name or method.__name__
            self.__doc__ = method.__doc__
        def __get__(self, inst, cls): 
            if inst is None:
                return self
            elif self.name in inst.__dict__:
                return inst.__dict__[self.name]
            else:
                result = self.method(inst)
                inst.__dict__[self.name]=result
                return result    
        def __set__(self, inst, value):
            raise AttributeError("This property is read-only")
        def __delete__(self,inst):
            del inst.__dict__[self.name]
    

    For example:

    if __name__=='__main__':
        class Foo(object):
            @ReadOnlyCachedAttribute
            # @read_only_lazyprop
            def bar(self):
                print 'Calculating self.bar'  
                return 42
        foo=Foo()
        print(foo.bar)
        # Calculating self.bar
        # 42
        print(foo.bar)    
        # 42
        try:
            foo.bar=1
        except AttributeError as err:
            print(err)
            # This property is read-only
        del(foo.bar)
        print(foo.bar)
        # Calculating self.bar
        # 42
    

    One of the beautiful things about CachedAttribute (and
    ReadOnlyCachedAttribute) is that if you del foo.bar, then the next time you
    access foo.bar, the value is re-calculated. (This magic is made possible by
    the fact that del foo.bar removes 'bar' from foo.__dict__ but the property
    bar remains in Foo.__dict__.)

    If you don’t need or don’t want this ability to recalculate,
    then the following (based on Mike Boers’ lazyprop) is a simpler way to make a read-only lazy property.

    def read_only_lazyprop(fn):
        attr_name = '_lazy_' + fn.__name__
        @property
        def _lazyprop(self):
            if not hasattr(self, attr_name):
                setattr(self, attr_name, fn(self))
            return getattr(self, attr_name)
        @_lazyprop.setter
        def _lazyprop(self,value):
            raise AttributeError("This property is read-only")
        return _lazyprop
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to create a decorator that will allow me to return a raw
I want to be able to create a python decorator that automatically registers class
I want to create a decorator that profiles a method and logs the result.
I want create wordpress website into which I want create user management... That means
i want create a custom json data from the mssql 2008 results so that
I want create module which update list of usb devices automatically (not only mass
I want to create a new field (or two) in my table that is
I would like to create a HtmlHelper function for a specific kind of dropdown
I want to create an IList of objects that are all different concrete types,
Given a Map[String, Int] in Scala, I want to create a trait that allows

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.