python deepcopy报错,Python:copy.deepcopy产生错误

本文探讨了Python中使用深拷贝方法时遇到的具体错误,并提供了详细的错误追踪信息。通过分析,指出了当尝试拷贝生成器时会出现的问题,并给出了相应的解决思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have been using this copy method for quite a while, in lots of classes that needed it.

class population (list):

def __init__ (self):

pass

def copy(self):

return copy.deepcopy(self)

It has suddenly started producing 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__()

>>>

the lines which include the references to lines 338, 162, 255, 189 were repeated quite a few times before the 'line 338' that I copied here.

解决方案

Are you cloning a generator? Generators can't be cloned.

Copying answer by Gabriel Genellina here:

There is no way of "cloning" a generator:

py> g = (i for i in [1,2,3])

py> type(g)()

Traceback (most recent call last):

File "", line 1, in

TypeError: cannot create 'generator' instances

py> g.gi_code = code

Traceback (most recent call last):

File "", line 1, in

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__

You can do that with a generator function because it acts as a "generator

factory", building a new generator when called. Even using the Python C

API, to create a generator one needs a frame object -- and there is no way

to create a frame object "on the fly" that I know of :(

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 and g2 share the same execution frame, so they're not independent. There

is no easy way to create a new frame in Python:

py> type(g.gi_frame)()

Traceback (most recent call last):

File "", line 1, in

TypeError: cannot create 'frame' instances

One could try using PyFrame_New -- but that's way too magic for my taste...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值