Lazy loading sample code for the Python method

  • 2020-06-19 10:40:20
  • OfStack

In the process of data mining, data processing is one of important link, we tend to encapsulate it into a method, and sometimes this one method may be called repeatedly, each one to deal with data that would be a very time-consuming and resource manipulation, so is there any way to cache the results of calculated up to call once, the effect of running everywhere, after 1 research in lazy_object_proxy/utils py found 1 piece of code, see lazy_object_proxy.


class cached_property(object):
  def__init__(self, func):
    self.func = func

  def__get__(self, obj, cls):
    if obj is None:
      return self
    value = obj.__dict__[self.func.__name__] = self.func(obj)
    return value

So how do you use it later? Here is a simple example:


class Test(object):
  def__init__(self,value):
    self.value = value;
@cached_property
  def display(self):
    #create expensive object
    print "some complicated compute here"
    return self.value

Here are the results


>> t = Test(1000)
>>t.display
some complicated compute here
1000
>>t.display
1000

As can be seen from the above results, only once some complicated compute here was printed, i.e. only once was called, which achieved our goal.


Related articles: