Hi there

This post is just meant to document my own newbie's steps in understanding Python and PyX, and maybe to enlighten others.

I often find myself composing graphics from similar elements: put a base set-up on a canvas, "copy" and modify different copies. Oh well, it turns out that Python instance references may bite you in the rear end. The easy way out is: insert the "base" canvas into two different canvases and modify those, but not the original base canvas.

The attached code demonstrates what can go wrong with a naive approach, which might be the one which noobs like me come up first. It simply does the following:

draw on canvas c
insert c into b
draw on canvas c
modify c's trafo
(display both on a)

Naively one would expect all operations on c after insertion into b to affect c only, not the "copy" in b. Alas, inserting produces a reference to the same instance, not a copy.

As an added bonus, the code shows the differences of two different attempts at inserting a real copy of c into b: shallow copies and deep copies.

The shallow copy of c creates a new instance whose "most parts" are references to elements of b. Modification of the trafo shows that it's still different from direct insertion (because these references can be changed).

The deep copy really has a life of its own, therefore changes to c after insertion don't change b. [The change of the bbox of c by the trafo changes the bbox of a, which is what you see, not the one of b.]

Cheers,
Michael

P.S.: deep copies are no good with threads, which implies: no good when texrunners are around!
from pyx import *
import copy

for key,code in [ ('direct',''), ('shallowcopy','copy.copy'), ('deepcopy','copy.deepcopy') ]:
  a = canvas.canvas()
  b = canvas.canvas()
  c = canvas.canvas()

  c.fill(path.circle(0,0,1))
  eval('b.insert(%s(c),[color.rgb.red])' % code)
  c.fill(path.rect(2,-1,2,2))
  c.trafo *= trafo.translate(0,1)

  a.insert(b)
  a.insert(c, [trafo.translate(6,0)])

  a.writeEPSfile("canvascopy-%s" % key)

<<inline: canvascopy-deepcopy.eps>>

<<inline: canvascopy-direct.eps>>

<<inline: canvascopy-shallowcopy.eps>>

-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
PyX-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/pyx-user

Reply via email to