473,543 Members | 1,975 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__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__(n ame, 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 2094
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__(n ame, 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__.ke ys():
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(Invert ed).

Oct 19 '08 #2

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

Similar topics

2
1494
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): self.str = str old = import copy
0
1336
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 ndict I delete adict. Then ndict contains a good copy of adict. works great.
6
3098
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 Canvas Object. Perhaps any Tkinter object, didn't get that far. The problem arises because I have a geometry tutorial with a progression of...
0
1375
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 be. Is there some nice way to make copy/deepcopy give more information when this error happens? I know what the top level object is, but presumably...
0
7412
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7355
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7594
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7697
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5889
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3394
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3394
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
648
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.