Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - AttributeError: 'function' object has no attribute 'deepcopy'

Tags:

python

I have a list of mutable objects which is an attribute of a class.

self.matriceCaracteristiques

I would like to keep a copy of it, so that the objects will change during execution as for the original list, but not their order in the list itself (that is what I want to preserve and "restore" after execution).

copy_of_matCar = self.matriceCaracteristiques[:] #to preserve the order of the objects 
#that will be changed during execution

When it's time to restore the list, I've tried making this:

self.matriceCaracteristiques = copy_of_matCar[:]

but it doesn't work cause although the copy_of_matCar has a different order (specifically, the one that the attribute had before some code execution), the other self.matriceCaracteristiques remains exactly the same although the instruction. So I have thought to make a deepcopy of it, by following the Python reference:

import copy
self.matriceCaracteristiques = copy.deepcopy(copy_of_matCar)

However, what I get is the following error:

  self.matriceCaracteristiques = copy.deepcopy(copy_of_matCar)
AttributeError: 'function' object has no attribute 'deepcopy'

Any idea how I can fix this problem and get a deepcopy of the list copy_of_matCar to be assigned to the self.matriceCaracteristiques one?

like image 399
Matteo NNZ Avatar asked Jan 27 '14 08:01

Matteo NNZ


3 Answers

I am facing the same problem, and tried many ways. The following way resolves my problem: change

import copy
dict = {...}
copy.deepcopy()

to

from copy import deepcopy
dict = {...}
deepcopy()
like image 110
weili zhang Avatar answered Nov 08 '22 13:11

weili zhang


What's been suggested in the comment is the source of the problem: there's something shadowing copy in your module, after you imported the copy module.

Consider for instance the following modules:

# In some_module_1.py
from copy import copy


# In some_module_2.py
import copy
# `copy` refers to the module, as expected
print('deepcopy' in dir(copy))  # True

from some_module_1 import *
# `copy` got shadowed, it is now actually referring to `copy.copy`
print('deepcopy' in dir(copy))  # False

Because I imported everything from some_module_1, I also imported the function copy I imported over there. This means it now shadows the module copy imported 4 lines above. Therefore python properly complains that deepcopy isn't an attribute of the function copy.copy, hence the error

AttributeError: 'function' object has no attribute 'deepcopy'
like image 29
Alvae Avatar answered Nov 08 '22 13:11

Alvae


Please find other copy module in your code. For example, ...

from numpy.lib.function_base import copy

Please remove other copy modules.

like image 41
Aleksey Revizhov Avatar answered Nov 08 '22 13:11

Aleksey Revizhov