473,396 Members | 1,940 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

__metaclass__ and deepcopy issue

I read the article on http://www.python.org/download/relea...o/#metaclasses
and started using autoprop.
But now I have a problem I can't seem to solve myself.

class autoprop(type):
def __init__(cls, name, bases, dict):
super(autoprop, cls).__init__(name, bases, dict)
props = {}
for name in dict.keys():
if name.startswith("_get_") or name.startswith("_set_"):
props[name[5:]] = 1
for name in props.keys():
fget = getattr(cls, "_get_%s" % name, None)
fset = getattr(cls, "_set_%s" % name, None)
setattr(cls, name, property(fget, fset))
class InvertedX:
__metaclass__ = autoprop
def _get_x(self):
return -self.__x
def _set_x(self, x):
self.__x = -x

a = InvertedX()
from copy import deepcopy
b = deepcopy(a)

The deepcopy gives an error inside copy.py of the python lib.

TypeError: descriptor '__reduce__' of 'object' object needs an
argument

Does anybody know how to solve this issue?
Oct 17 '08 #1
1 2090
On Oct 17, 1:00*am, Wouter DW <wouter.dewi...@gmail.comwrote:
I read the article onhttp://www.python.org/download/releases/2.2/descrintro/#metaclasses
and started using autoprop.
But now I have a problem I can't seem to solve myself.

class autoprop(type):
* def __init__(cls, name, bases, dict):
* * super(autoprop, cls).__init__(name, bases, dict)
* * props = {}
* * for name in dict.keys():
* * * if name.startswith("_get_") or name.startswith("_set_"):
* * * * props[name[5:]] = 1
* * for name in props.keys():
* * * fget = getattr(cls, "_get_%s" % name, None)
* * * fset = getattr(cls, "_set_%s" % name, None)
* * * setattr(cls, name, property(fget, fset))
class InvertedX:
* __metaclass__ = autoprop
* def _get_x(self):
* * return -self.__x
* def _set_x(self, x):
* * self.__x = -x

a = InvertedX()
from copy import deepcopy
b = deepcopy(a)

The deepcopy gives an error inside copy.py of the python lib.
Hmm, your code works just fine for me in Py2.6.
If I add "a.x = 10" before the deepcopy and
"print b.x" after the deepcopy, it also shows
the desired result.

>
TypeError: descriptor '__reduce__' of 'object' object needs an
argument

Does anybody know how to solve this issue?
Usually, when you get errors of this kind with copy, deepcopy, or
pickle, it means that the copier can't figure out how to extract
the relevant components and then re-assemble them into a new instance.

This means that you need to define some combination of __copy__,
__deepcopy__, __reduce__, __getstate__, __setstate__, __getinitargs__,
and/or __getnewargs__. See the pickle module and copy module for
all the gory details.

One other thought, class decorators can be much easier to use and
understand than an equivalent metaclass:

def autoprop(cls):
for name in cls.__dict__.keys():
if name.startswith("_get_") or name.startswith("_set_"):
name = name[5:]
fget = getattr(cls, "_get_%s" % name, None)
fset = getattr(cls, "_set_%s" % name, None)
setattr(cls, name, property(fget, fset))
return cls

@autoprop
class InvertedX:
def _get_x(self):
return -self.__x
def _set_x(self, x):
self.__x = -x

a = InvertedX()
a.x = 10
print a.x
from copy import deepcopy
b = deepcopy(a)
print b.x
Raymond
P.S. Minor nits in the original code. When you use a dict like
"props" but care only about the key, not the value, that usually means
that you're better-off with a set() than a dict(). Also, you don't
even need to build-up "props" since the values can be used immediately
(like in my example code). But the most important part is that
whenever you're using metaclasses for registration, validation, or
simple transformation (as in your example), then a simple class
decorator is often a better choice. If you don't have Py2.6 yet, then
you can get the same effect by defining the class and *then* writing,
"Inverted = autoprop(Inverted).

Oct 19 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Eugeni Doljenko | last post by:
There is a list of custom objects. I want do duplicate this list to modify objects in new list and then compare old and new. I could do it with deepcopy class foo: def __init__(self, str):...
0
by: phil | last post by:
I wrote the following to prove to myself that deepcopy would copy an entire dictionary which contains an instance of a class to one key of another dictionary. Note that after copying adict to...
6
by: phil | last post by:
I posted the following yesterday and got no response and did some testing simplifying the circumstances and it appears that deepcopy fails when the object to be copied contains a reference to a...
0
by: Robin Becker | last post by:
I'm using deepcopy in some code which eventually ends up by crash witht he following rather long winded error. I'm not directly using _hashlib.HASH, but I suppose something else along the way could...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.