A lazy loading configuration design

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed.

It can contribute to efficiency in the program's operation if properly and appropriately used.

class LazyProperty(object):
	def __init__(self, function):
		self.function = function
		self.name = function.__name__

	def __get__(self, obj, type=None) -> object:
		if obj is None:
			return self
		value = self.function(obj)
		setattr(obj, self.name, value)
		return value

class Configurations:
	@LazyProperty
	def deavy_config(self):
		print("loading heave config..")
		# simulate the delay with sleep
		import time
		time.sleep(2)
		return {"data": "heavy config data"}

config = Configurations()

# At this point, the heavy config hasn't been loaded yet
print("Accessing heavy_config property...")
print(config.heavy_config)
print("Access heavy_config again...")
print(config.heavy_config)

In this example, the heavy_config isn't loaded when the Configurations instance is created. It's only loaded when it's first accessed via config.heavy_config. After it's loaded once, it won't be loaded again, as it's saved in the config instance's attributes.

Advantage of Lazy Loading

You can save resources by not loading heavy configuration until they're actually needed.