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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T23:26:51+00:00 2026-05-24T23:26:51+00:00

I wanted to implement lazy loading of variables, but I seem to misunderstand descriptors

  • 0

I wanted to implement lazy loading of variables, but I seem to misunderstand descriptors a bit. I’d like to have object variables, which on first access will call the obj.load() function which will initialize the variables with their real value. I wrote

class ToLoad(object):
    def __init__(self, loader_name="load")
        self.loader_name=loader_name

    def __get__(self, obj, type):
        if not (hasattr(obj, "_loaded") and obj._loaded):
            obj._loaded=True
            getattr(obj, self.loader_name)()
        return None

class Test(object):
    x=ToLoad()
    def __init__(self, y):
        self.y=y

    def load(self):
        print("Loading {}".format(self.y))
        self.x=self.y

t1=Test(1)
t2=Test(2)
print("A", t1.x)
print("B", t2.x)
print("C", t1.x)

which fails to return the actual value on loading at least the first time. Could someone suggest another way to solve that problem? I’m not sure how to return the correct value in get since at that point I do not know that the attribute is called “x”? Any other way?

DAMN, can’t answer my own question… So here is the
EDIT:
Thanks for the input! However, my load() function does not return the variable itself, since it loads many different variables. And I want to minimize the notation for using lazy loading. So I came up with a decorator

class to_load:
    def __init__(self, *vars, loader="load"):
        self.vars=vars
        self.loader=loader

    def __call__(self, cls):

        def _getattr(obj, attr):
            if attr in self.vars:
                getattr(obj, self.loader)()
                return getattr(obj, attr)
            else:
                raise AttributeError

        cls.__getattr__=_getattr
        return cls

@to_load("a", "b")
class Test:
    def load(self):
        print("Loading")
        self.a=1
        self.b=2

t=Test()
print("Starting")
print(t.a)
print(t.b)
#print(t.c)

Is that OK? I’m not sure if I’m breaking things.

  • 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-24T23:26:52+00:00Added an answer on May 24, 2026 at 11:26 pm

    Well, there are two problems here:

    1. You return None from __get__, whereas it should be the value you want x to represent.
    2. You do x = y, but your descriptor doesn’t implement __set__.

    So, instead of setting a “is loaded” flag, you should rather create an attribute with the actual value, and check for that. If you don’t want it to be read-only, you should implement __set__. Otherwise, instead of self.x = self.y in load, return the value and let __get__ to take care of the assignment.

    class ToLoad(object):
        def __init__(self, var, func):
            self.var  = var
            self.func = func
    
        # style note: try to avoid overshadowing built-ins (e.g. type)
        def __get__(self, obj, cls):
            try:
                return getattr(obj, self.var)
            except AttributeError:
                value = getattr(obj, self.func)()
                setattr(obj, self.var, value)
                return value
    
    class Foo(object):
        x = ToLoad('x', '_load_x')
    
        def __init__(self, y):
            self.y = y
    
        def _load_x(self):
            print('Loading {0} into x'.format(self.y))
            return self.y
    
    a = Foo(1)
    b = Foo(2)
    print(a.x)
    print(b.x)
    print(a.x)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an ImageView for which I wanted to implement the onClickListener. But when
I wanted to implement a Node type like written below but I want to
Hi I wanted to implement a loop which is extremely large in thrust but
I always wanted to implement swypable tabs in my application, like the ones in
Let's say you wanted to implement a breadth-first search of a binary tree recursively
i wanted to implement charts in my silverlight app. i have installed SL4 in
If I wanted to implement a JDBC Driver, how would I know which interfaces/abstract
so I wanted to implement tab views on my app. But I realised the
I'm new to unit testing in general, but wanted to implement it in MVC
I am exploring iOS4.3 SDK & wanted to implement a particular animation effect. But

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.