(begginer) issue with pickling class objects

François Granger francois.granger at free.fr
Sun Apr 8 15:49:28 EDT 2001


I send below a simplified version of the code I am writing. When I run
it I get the following error message:
'Failed to import class B from module __main__'
I tired an alternative wich is commented out (line 44-51 , 61 and 65)
but the error message is similar with a reference to class A.

I am guessing that this is an issue with namespace that I don't really
understand.

On a similar track, I would be happy to see a more general algorithm to
implement persistence of complexe objects between runs.

TIA


========================================================
# python
"""
Simple test of pickling complex objects

"""
import pickle

class A:
    """
    """
    id = 0
    def __init__(self):
        A.id += 1
        self.value = 0.0
        self.id = A.id
    
    def __repr__(self):
        return str(self.__dict__) + '\n\n'
    
    def activate(self):
        self.value += 1.0


class B:
    """
    """
    def __init__(self,  ninput = 10, noutput = 10):
        self.ninput = ninput
        self.noutput = noutput
        self.input = {}
        for i in range(self.ninput):
            self.input[A.id] = A()
        self.output = {}
        for i in range(self.noutput):
            self.output[A.id] = A()
    
    def transmit(self):
        for i in self.input.keys():
            self.input[i].activate()
        
        for i in self.output.keys():
            self.output[i].activate()
    """
    def save_NN(self, fp):
        pickle.dump((self.input, self.output), fp)
        pass
    
    def load_NN(self, fp):
        #set neuron.id to max id ?
        self.input, self.layer, self.output = pickle.load(fp)
        pass
    """

if __name__ == '__main__':
    inp = 10
    out = 10
    N = B(inp, out)
    for i in range(5):
        N.transmit()
    fp = open('neuronet.txt', 'w')
    #N.save_NN(fp)
    pickle.dump(N, fp)
    fp.close()
    fp = open('neuronet.txt', 'r')
    #N.load_NN(fp)
    N = pickle.load(fp)
    fp.close()
    pass

========================================================

-- 
[fr, en, es, ia]
Information sur la hiérarchie usenet europa.* :
http://europa.usenet.eu.org



More information about the Python-list mailing list