Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error trying to pickle a user defined class

I’ve just started to use pickle, and I’m trying to pickle a class I defined on my own so that I can unpickle it in a Flask App.

This is the code for my class:

class wma :

    def __init__(self) : pass

    def isConsistent(self, df, nConsecutive) :
        sum = 0
        for i in np.arange(1, nConsecutive + 1) :
            sum += i

        weights = []
        for val in np.arange(1, nConsecutive + 1) :
            weight = val / sum
            weights.append(weight)
        
        maxWMA = 0
        for weight in weights :
            maxWMA += weight

        result = df[0].rolling(nConsecutive).apply(lambda x : np.sum(weights * x))
        currentWMA = results.iloc[-1]

        if currentWMA == maxWMA :
            return True
        else :
            return False

And here’s me trying to pickle it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

wma = wma()
file = open("wma", "wb")
pickle.dump(wma, file)
file.close()

But this gives me the error:

PicklingError: Can't pickle <class '__main__.wma'>: it's not the same object as __main__.wma

I’m new to pickling so I’m not sure what’s wrong. Any suggestions to resolve the error?

>Solution :

Having a class and an instance of that class with the same name is a bad idea in general, but specifically in this case. Pickling depends on type names being available in the global scope, so when it sees that wma is a variable reporting to be of type wma (a type whose name no longer exists since we just overwrote it), it gets confused.

Just name the variable anything else and you’ll be fine.

my_wma = wma()
file = open("wma", "wb")
pickle.dump(my_wma, file)
file.close()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading