Lex Lex - 1 month ago 13
Python Question

Pre-Calculated Objects in Python

Is there a way to pre-calculate an object in Python?

Like when you use a constructor just like:

master = Tk()


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

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.

Answer

I think what you're looking for is the pickle module to serialize an object. In Python 2 there is pickle and cPickle, which is the same but faster, but iirc Python 3 only has pickle (which, under the hood, is equivalent to cPickle from Python 2). This would allow you to save an object with its pre-calculated attributes.

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)
Comments