Note that there are some explanatory texts on larger screens.

plurals
  1. POpython lazy variables? or, delayed expensive computation
    primarykey
    data
    text
    <p>I have a set of arrays that are very large and expensive to compute, and not all will necessarily be needed by my code on any given run. I would like to make their declaration optional, but ideally without having to rewrite my whole code.</p> <p>Example of how it is now:</p> <pre><code>x = function_that_generates_huge_array_slowly(0) y = function_that_generates_huge_array_slowly(1) </code></pre> <p>Example of what I'd like to do:</p> <pre><code>x = lambda: function_that_generates_huge_array_slowly(0) y = lambda: function_that_generates_huge_array_slowly(1) z = x * 5 # this doesn't work because lambda is a function # is there something that would make this line behave like # z = x() * 5? g = x * 6 </code></pre> <p>While using lambda as above achieves one of the desired effects - computation of the array is delayed until it is needed - if you use the variable "x" more than once, it has to be computed each time. I'd like to compute it only once.</p> <p>EDIT: After some additional searching, it looks like it is possible to do what I want (approximately) with "lazy" attributes in a class (e.g. <a href="http://code.activestate.com/recipes/131495-lazy-attributes/" rel="noreferrer">http://code.activestate.com/recipes/131495-lazy-attributes/</a>). I don't suppose there's any way to do something similar without making a separate class?</p> <p>EDIT2: I'm trying to implement some of the solutions, but I'm running in to an issue because I don't understand the difference between:</p> <pre><code>class sample(object): def __init__(self): class one(object): def __get__(self, obj, type=None): print "computing ..." obj.one = 1 return 1 self.one = one() </code></pre> <p>and</p> <pre><code>class sample(object): class one(object): def __get__(self, obj, type=None): print "computing ... " obj.one = 1 return 1 one = one() </code></pre> <p>I think some variation on these is what I'm looking for, since the expensive variables are intended to be part of a class.</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.
 

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