Pickle, __init__, and classes

Y

Yin

I've created a class that reads in and processes a file in the
initializer __init__. The processing is fairly substantial, and thus,
instead of processing the file every time the object is created, I
pickle the object to a file.

In subsequent creations of the object, I implement a test to see
whether the pickled file exists. If it does, then I unpickle the
object.

Unfortunately, the __init__ cannot return this unpickled object.

I've used an auxiliary member function which fixes the problem, but I
would prefer to have the correct object returned at instantiation
rather than returned from the auxiliary member function.

Are there other ways of approaching this problem?

Thanks,
Yin
 
R

Russell Blau

Yin said:
I've created a class that reads in and processes a file in the
initializer __init__. The processing is fairly substantial, and thus,
instead of processing the file every time the object is created, I
pickle the object to a file.

In subsequent creations of the object, I implement a test to see
whether the pickled file exists. If it does, then I unpickle the
object.

Unfortunately, the __init__ cannot return this unpickled object.

Try __new__(). http://docs.python.org/ref/customization.html This isn't
the usual application of __new__, but since it returns an object it should
be ideal for your purposes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top