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 tutorial makes a clean and elegant solution
possible. Other solutions I am trying to come up with are
very messy.
It is frustrating to think that in a language like python
there might be things which you can't make a copy of.
That is bizarre enough to wonder about a deep flaw or
hopefully I'm just doing something very wrong.
Any ideas appreciated.
phil wrote: 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['x'] I delete adict. Then ndict['x'] contains a good copy of adict. works great.
class aclass: def __init__(s): s.anint = 123 aninstance = aclass() adict = {} adict['y'] = aninstance
ndict = {} ndict['x'] = copy.deepcopy(a dict) del adict print ndict print ndict['x']['y'] print ndict['x']['y'].anint # this line prints 123 print
Then in the following code when I try to deepcopy s.glob.objs I get following error Note that s.glob.objs is a dictionary and I am attempting to copy to a key of s.save, another dict, just like above. ?????????? s.glob.objs may have several keys, the data for each will be instance of classes like line and circle. Those instances will have tkinter canvas objects in them.
class Graph: def __init__(s): class DummyClass: pass s.glob = DummyClass() s.glob.objs = {} .. # here add some instance of objects like .. # circles and lines to s.glob.objs # instantiate dialog s.DI = dialog(s.glob)
class dialog: def __init__(s,glob ): s.glob = glob s.save = {}
def proc(s): cur = someint s.save[cur] = copy.deepcopy(s .glob.objs)
Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args ) File "/home/phil/geo/g.py", line 303, in enter else:s.proc() File "/home/phil/geo/g.py", line 245, in proc s.save[cur][k] = copy.deepcopy(s .glob.objs[k][0]) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst state = deepcopy(state, memo) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 307, in _deepcopy_inst state = deepcopy(state, memo) File "/usr/local/lib/python2.3/copy.py", line 179, in deepcopy y = copier(x, memo) File "/usr/local/lib/python2.3/copy.py", line 270, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/local/lib/python2.3/copy.py", line 206, in deepcopy y = _reconstruct(x, rv, 1, memo) File "/usr/local/lib/python2.3/copy.py", line 338, in _reconstruct y = callable(*args) File "/usr/local/lib/python2.3/copy_reg.py", line 92, in __newobj__ return cls.__new__(cls , *args) TypeError: function() takes at least 2 arguments (0 given)
6 3110
phil wrote: It is frustrating to think that in a language like python there might be things which you can't make a copy of. That is bizarre enough to wonder about a deep flaw or hopefully I'm just doing something very wrong.
To be honest, it doesn't really surprise me that you cannot copy Tkinter
objects. If you could make a copy of an object which is displayed on the
screen I would expect that copying would create another object on the
screen, and that probably isn't what you want. Other uncopyable objects
include files, stack frames and so on.
The deepcopy protocol does allow you to specify how complicated objects
should be copied. Try defining __deepcopy__() in your objects to just copy
the reference to the Canvas object instead of the object itself. The deepcopy protocol does allow you to specify how complicated objects should be copied. Try defining __deepcopy__() in your objects to just copy the reference to the Canvas object instead of the object itself.
I can't figure out from the docs what __deepcopy__ is or how it
works.
I have about 25 classes of drawn objects. for instance
class linefromslope creates an instance of class line.
One of my "ugly solutions" involves a class prop: within each class,
put properties like slope and midpoint within the self.prop instance
and making a copy of that.
Would __deepcopy__ facilitate this?
Or am I assuming too much: is __deepcopy__ just a method
I invent to do what I want?
phil wrote: The deepcopy protocol does allow you to specify how complicated objects should be copied. Try defining __deepcopy__() in your objects to just copy the reference to the Canvas object instead of the object itself. I can't figure out from the docs what __deepcopy__ is or how it
works. I have about 25 classes of drawn objects. for instance class linefromslope creates an instance of class line. One of my "ugly solutions" involves a class prop: within each class, put properties like slope and midpoint within the self.prop instance and making a copy of that. Would __deepcopy__ facilitate this? Or am I assuming too much: is __deepcopy__ just a method I invent to do what I want?
The docs say:
In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument.
__deepcopy__ is a method which overrides the default way to make a deepcopy
of an object.
So, if you have a class with attributes a, b, and c, and you want to ensure
that deepcopy copies a and b, but doesn't copy c, I guess you could do
something like: class MyClass:
_dontcopy = ('c',) # Tuple of attributes which must not be copied
def __deepcopy__(se lf, memo):
clone = copy.copy(self) # Make a shallow copy
for name, value in vars(self).iter items():
if name not in self._dontcopy:
setattr(clone, name, copy.deepcopy(v alue, memo))
return clone
class Copyable(object ):
def __new__(cls, *args):
print "created new copyable"
return object.__new__( cls, *args)
m = MyClass() m.a = Copyable()
created new copyable m.b = Copyable()
created new copyable m.c = Copyable()
created new copyable clone = copy.deepcopy(m )
created new copyable
created new copyable m.a is clone.a
False m.c is clone.c
True
As you can see, the deepcopy only creates deep copies of 2 of the 3
attributes, 'c' is simply copied across as a shallow copy.
and if you subclass MyClass you can modify the _dontcopy value to add
additional attributes which must not be copied.
phil wrote: I posted the following yesterday and got no response
When you don't get as much of a response as you expected, you might
consider the advice here: http://www.catb.org/~esr/faqs/smart-questions.html
Pointing you here is only meant to be helpful. If you don't feel the
advice applies to you, feel free to ignore it, but you clearly haven't
been getting the results from this forum that you expected.
--
Michael Hoffman
> but you clearly haven't been getting the results from this forum that you expected.
Yes I have, this is a wonderful forum.
I was just providing more info due to more testing.
Thanks, I used some of your methods and believe it is now
working.
I also did a lot of experiments, which I've needed to do,
investigating when references vs values are passed and
returned. Not as obvious as I thought.
Duncan Booth wrote: phil wrote:
The deepcopy protocol does allow you to specify how complicated objects should be copied. Try defining __deepcopy__() in your objects to just copy the reference to the Canvas object instead of the object itself.
I can't figure out from the docs what __deepcopy__ is or how it
works. I have about 25 classes of drawn objects. for instance class linefromslope creates an instance of class line. One of my "ugly solutions" involves a class prop: within each class, put properties like slope and midpoint within the self.prop instance and making a copy of that. Would __deepcopy__ facilitate this? Or am I assuming too much: is __deepcopy__ just a method I invent to do what I want?
The docs say:
In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__( ) implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument.
__deepcopy__ is a method which overrides the default way to make a deepcopy of an object.
So, if you have a class with attributes a, b, and c, and you want to ensure that deepcopy copies a and b, but doesn't copy c, I guess you could do something like:
class MyClass: _dontcopy = ('c',) # Tuple of attributes which must not be copied
def __deepcopy__(se lf, memo): clone = copy.copy(self) # Make a shallow copy for name, value in vars(self).iter items(): if name not in self._dontcopy: setattr(clone, name, copy.deepcopy(v alue, memo)) return clone
class Copyable(object ): def __new__(cls, *args): print "created new copyable" return object.__new__( cls, *args)
m = MyClass() m.a = Copyable() created new copyable m.b = Copyable() created new copyable m.c = Copyable() created new copyable clone = copy.deepcopy(m ) created new copyable created new copyable m.a is clone.a False m.c is clone.c
True
As you can see, the deepcopy only creates deep copies of 2 of the 3 attributes, 'c' is simply copied across as a shallow copy.
and if you subclass MyClass you can modify the _dontcopy value to add additional attributes which must not be copied. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: OKB (not okblacke) |
last post by:
I've noticed some peculiar behavior from copy.deepcopy: if you pass
it a method or function object, it raises a TypeError somewhere in
copy_reg saying "function() takes at least 2 arguments (0 given)". I'm
guessing this is the constructor for functions, and it's somehow being
incorrectly called, but I'm not really sure.
This behavior is annoying, however. I realize the deepcopy
documentation warns that it doesn't handle copying certain...
|
by: Dan Perl |
last post by:
Here is some code to illustrate a problem that I have:
import copy
class myc:
def __init__(self):
self.myf=file('bar.txt',"w")
def foo(self):
self.myf.write('hello world!') # it's going to fail for
d.foo( )
c = myc()
|
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 |
last post by:
(see end of message for example code)
When an instance has a dynamically assigned instance method, deepcopy
throws a TypeError with the message "TypeError: instancemethod
expected at least 2 arguments, got 0". Tested with Python 2.3.4 on
OpenBSD and Python 2.4 on Win98; same results. Is this a bug in
deepcopy, how I dynamically assign the instance method or something
else? (See example code for how I did it.)
If you're curious as...
|
by: Alexander Zatvornitskiy |
last post by:
Hello!
I have trouble with copy/deepcopy. It seems, I just don't understand something.
Please explain where things goes wrong and how to do it the right way.
I have one class:
class Distribution:
__gr_on_transp=dict()
__ostatok_m=dict()
|
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.
| |
by: Joshua Ginsberg |
last post by:
Howdy --
I have a class that has an attribute that is a dictionary that contains
an object that has a kword argument that is a lambda. Confused yet?
Simplified example:
import copy
class Foo:
def __init__(self, fn=None):
|
by: none |
last post by:
I have a very complex data structure which is basically a class object
containing (sometimes many) other class objects, function references,
ints, floats, etc. The man for the copy module states pretty clearly
that it will not copy methods or functions. I've looked around for a
while (prob just using the wrong keywords) and haven't found a good
solution. As a workaround I've been using cPickle, loads(dumps(obj))
which is incredibly slow...
|
by: Stef Mientki |
last post by:
hello,
I'm trying to build a simple functional simulator for JAL (a Pascal-like language for PICs).
My first action is to translate the JAL code into Python code.
The reason for this approach is that it simplifies the simulator very much.
In this translation I want to keep the JAL-syntax as much as possible intact,
so anyone who can read JAL, can also understand the Python syntax.
One of the problems is the alias statement, assigning a...
|
by: Wouter DW |
last post by:
I read the article on http://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_"):
|
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 usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
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();...
|
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...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| | |