Python: copy.deepcopy creates an error

I have been using this copying method for quite some time, in many classes that it needs.

class population (list):
def __init__ (self):
    pass

def copy(self):
    return copy.deepcopy(self)

He unexpectedly started this error:

     File "C:\Python26\lib\copy.py", line 338, in _reconstruct
    state = deepcopy(state, memo)
  File "C:\Python26\lib\copy.py", line 162, in deepcopy
    y = copier(x, memo)
  File "C:\Python26\lib\copy.py", line 255, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "C:\Python26\lib\copy.py", line 189, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "C:\Python26\lib\copy.py", line 323, in _reconstruct
    y = callable(*args)
  File "C:\Python26\lib\copy_reg.py", line 93, in __newobj__
    return cls.__new__(cls, *args)
TypeError: object.__new__(generator) is not safe, use generator.__new__()
>>> 

lines that include links to lines 338, 162, 255, 189 were repeated quite a few times before the “line 338” that I copied here.

+3
source share
2 answers

Do you clone a generator? Generators cannot be cloned.

Copy Gabriel Genellina's answer here:


There is no way to "clone" a generator:

py> g = (i for i in [1,2,3])
py> type(g)()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: cannot create 'generator' instances
py> g.gi_code = code
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: readonly attribute
py> import copy
py> copy.copy(g)
Traceback (most recent call last):
...
TypeError: object.__new__(generator) is not safe, use generator.__new__()
py> type(g).__new__
<built-in method __new__ of type object at 0x1E1CA560>

, "" factory ", . Python C
API, - " ", : (

py> import ctypes
py> PyGen_New = ctypes.pythonapi.PyGen_New
py> PyGen_New.argtypes = [ctypes.py_object]
py> PyGen_New.restype = ctypes.py_object
py> g = (i for i in [1,2,3])
py> g2 = PyGen_New(g.gi_frame)
py> g2.gi_code is g.gi_code
True
py> g2.gi_frame is g.gi_frame
True
py> g.next()
1
py> g2.next()
2

g g2 , .
Python:

py> type(g.gi_frame)()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: cannot create 'frame' instances

PyFrame_New - ...

+9

, . , PIL PixelAccess Image .

, pixels = image.load(). , - pixels_copy = copy.copy(pixels), , . , pixels_copy = image.copy().load().

0

Source: https://habr.com/ru/post/1717290/


All Articles