Caching result of a method in Python

def get_obj():
model_obj = model() # Some large database query
return model_obj
def get_obj_value(self):
obj = self.get_obj()
return obj
def get_obj_value_dup(self):
obj = self.get_obj()
return obj
def memoize(function):
memo = {}
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper@memoize
def get_obj():
model_obj = model()
return model_obj
def get_obj_value(self):
obj = self.get_obj()
return objdef get_obj_value_dup(self):
obj = self.get_obj()
return obj
from functools import cached_property@cached_property
def get_obj():
model_obj = model()
return model_obj

--

--

--

Graduate from The National Institute of Engineering. Currently, I am working as a backend developer in a FinTech firm.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

[DEG] Let’s Play: Ancient Greek Punishment: Teaches Typing

Opportunistic Testing

News:Global Applicant Tracking System Market is estimated to reach USD 2.1 Billion by 2025

Recap of Torum’s Exclusive Access Program (Backend Migration)

Solving a “Respectable” Codility Challenge in One Line of Code

Using Feature Flags to reduce deployment risks

DASH101 — Part 3: Add interactivity with Dash callback

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
anurag kumar

anurag kumar

Graduate from The National Institute of Engineering. Currently, I am working as a backend developer in a FinTech firm.

More from Medium

Mutable vs Immutable Objects in Python

Explain Function in Python

Your First Python Tutorial

Deciding the best Singleton Approach in Python