Pre-Calculated Objects in Python
<p>Is there a way to pre-calculate an object in Python?</p>

<p>Like when you use a constructor just like:</p>

<pre><code>master = Tk()
</code></pre>

<p>Is there a way to pre-calculate and save the object and read it on startup instead of creating it?</p>

<p>My mind is all about saving work, or doing it in advance for the CPU. Oh and if you know a scenario where this is actually done i'd love to hear about it.</p>

<p>I think what you're looking for is the <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow"><code>pickle</code> module</a> to serialize an object. In Python 2 there is <code>pickle</code> and <code>cPickle</code>, which is the same but faster, but iirc Python 3 only has <code>pickle</code> (which, under the hood, is equivalent to <code>cPickle</code> from Python 2). This would allow you to save an object with its pre-calculated attributes.</p>

<pre><code>import cPickle as pickle
import time

class some_object(object):
    def __init__(self):
        self.my_val = sum([x**2 for x in xrange(1000000)])

start = time.time()

obj = some_object()

print "Calculated value = {}".format(obj.my_val)
with open('saved_object.pickle', 'w') as outfile: #Save the object
    pickle.dump(obj, outfile)

interim = time.time()

reload_obj = pickle.load(open('saved_object.pickle','r'))

print "Precalculated value = {}".format(reload_obj.my_val)

end = time.time()

print "Creating object took {}".format(interim - start)
print "Reloading object took {}".format(end - interim)
</code></pre>

python optimization