Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first half of your problem (reusing the value) is easily solved:</p> <pre><code>class LazyWrapper(object): def __init__(self, func): self.func = func self.value = None def __call__(self): if self.value is None: self.value = self.func() return self.value lazy_wrapper = LazyWrapper(lambda: function_that_generates_huge_array_slowly(0)) </code></pre> <p>but you still have to use it as <code>lazy_wrapper()</code> not <code>lasy_wrapper</code>.</p> <p>If you're going to be accessing some of the variables many times, it may be faster to use:</p> <pre><code>class LazyWrapper(object): def __init__(self, func): self.func = func def __call__(self): try: return self.value except AttributeError: self.value = self.func() return self.value </code></pre> <p>which will make the first call slower and subsequent uses faster.</p> <p><strong>Edit:</strong> I see you found a similar solution that requires you to use attributes on a class. Either way requires you rewrite every lazy variable access, so just pick whichever you like.</p> <p><em><strong>Edit 2:</em></strong> You can also do:</p> <pre><code>class YourClass(object) def __init__(self, func): self.func = func @property def x(self): try: return self.value except AttributeError: self.value = self.func() return self.value </code></pre> <p>if you want to access <code>x</code> as an instance attribute. No additional class is needed. If you don't want to change the class signature (by making it require <code>func</code>, you can hard code the function call into the property.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload