473,788 Members | 2,810 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 2105
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
1506
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
1353
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
3111
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 drawings and want the students to be able to go "back". Creating "snapshots" of points in time in the...
0
1390
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 it's something further down that's causing the problem. .......... File...
0
9498
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10364
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.