How to create lazy class variables?

Viewed 45

I have a class with class variables that should be lazily created. I have a working version for instance variables. How do you implement one for class variables? The following is an example usage.

print(MyDatabase.users) # first call should load the users variable and return value
print(MyDatabase.users) # second call should return the stored value

The first error I got when I tried is AttributeError: type object 'MyDatabase' has no attribute 'users' . Is there a way to catch the error in the class?

1 Answers

Use @property like so:

class MyDatabase:

    def __init__(self):
        self._users = None

    @property
    def users(self):
        if self._users is None:
            # load users
            print('users loaded')
            self._users = ['u']
        return self._users


db = MyDatabase()

print(db.users)  # first call should load the users variable and return value
print(db.users)  # second call should return the stored value

The loading happens only the first time:

users loaded
['u']
['u']
Related