pythonclassobjectdeep-copy

using __deepcopy__ on custom object in python?


I am a writing a custom Queue class that uses list as a composite attribute. I do not sublcass from list. my code is here. I get the error for deepcopy which I have pasted below. can someone help me about what I is going wrong? Thanks

from iterator import Iterator
class Abstractstruc(object):
    def __init__(self):
        assert False
    def __str__(self):
        return "<%s: %s>" %(self.__class__.__name__,self.container)

class Queue(Abstractstruc,Iterator):

    def __init__(self,value=[]):
        self.container=[]
        self.size=0
        self.concat(value)

    def add(self, data):
            self.container.append(data)

    def  remove(self):
        self.container.pop(0)


    def peek(self):
        return self.container[0]


    def __getitem__(self,index):
        return self.container[index]


    def __iter__(self):
        return Iterator(self.container)

    def concat(self,value):
        for i in value:
            self.add(i)

    def __bool__(self):
        return len(self.container)>0

    def __len__(self):
        return len(self.container)


    def __deepcopy__(self,memo):
        return Queue(copy.deepcopy(self.container,memo))


if __name__=='__main__':
    q3=Queue()

    li=[1,2,3]
    q3.add(li)
    print q3 
    print len(q3)

    q4=copy.deepcopy(q3)
    q3.peek()[0]=100


    print "after modifying"
    print q3
    print "q4 = ", q4

output:

<Queue: [[1, 2, 3]]>
1
Traceback (most recent call last):
  File "test.py", line 56, in <module>
    q4=copy.deepcopy(q3)
NameError: name 'copy' is not defined

Solution

  • You need to import the copy module:

    import copy
    

    The error message:

    Traceback (most recent call last):
      File "test.py", line 56, in <module>
        q4=copy.deepcopy(q3)
    NameError: name 'copy' is not defined
    

    NameError is raised when Python does not know what the bare name copy refers to.