SchreiberLex
SchreiberLex

Reputation: 512

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.

Upvotes: 2

Views: 345

Answers (1)

roganjosh
roganjosh

Reputation: 13175

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)

Upvotes: 3

Related Questions