RoKa
RoKa

Reputation: 135

read a dict into self

I have a class that is doing a lot of stuff. In the end, it saves everything into a pickle. When I rerun this class I want to read the pickle instead of doing everything again. Unfortunately it the variable is always empty if I unpickle. Why is that so?

import pandas as pd

class Test:
    def __init__(path, value):
        # path points to a .txt file but its in the same folder as the pickle
        data_path, data = os.path.split(path)
        pickle_path = os.path.join(data_path, name.split('.')[1] + '.pickle'
        if os.path.isfile(pickle_path):
            self = pd.read_pickle(path)
        else:
            # do a ton of stuff and safe it as pickle afterwards

variable = Test(path, value)

In this case variable is empty if I read from pickle but correct if I do all the stuff...

Upvotes: 0

Views: 65

Answers (1)

Yang Yushi
Yang Yushi

Reputation: 765

If I want to cache some calculation results I will load/dump the object outside the class, something like,

pickle_path = os.path.join(data_path, name.split('.')[1] + '.pickle'
if os.path.isfile(pickle_path):
    with open(pickle_path, 'rb') as f:
        variable = pickle.load(f)  # use cached results
else:
    variable = Test()  # do all the calculations

Upvotes: 1

Related Questions