On 9/27/07, Jason Grout wrote:
> ...
> >
> >> where the union function returns the modified graph each time so I can
> >> keep chaining union function calls.  The union actually modifies the
> >> graph A, so if you want A left alone and a new graph returned, you do:
> >>
> >> newgraph=A.copy().union(B).union(C).union(D).union(E)
> >>
> >> Comments?  Is there a better way to do things?
> >
> > I would rather union returns a new object rather than modifying A,
> > it's much easier to reason about code that way, and fits better with
> > the rest of SAGE. One could provide a different method to do union in
> > place if one needs.
>
> I guess this brings up a much more general issue of conventions in SAGE
> (in general, should methods modify an object in-place or pass back a new
> object?).  I'll post up a new thread to try to clarify and get feedback
> on what conventions there are/should be.
>

There is another very relevant thread started by Robert Bradshaw  on
this list concerning the safety of in-place modifications:

http://groups.google.com/group/sage-devel/browse_thread/thread/806cd958eb28ac3b/46655d7572d11ee6?#46655d7572d11ee6

http://www.sagemath.org:9002/sage_trac/ticket/624

In general one wants to do as much in-place modification as possible
without risking unintended side-effects in other parts of the code.
Since Python maintains a reference count for every object, this means
that it is possible for an operation to know whether doing an in-place
modification represents a risk. If there is no external reference to
the object then there is no risk, so the operation should be done
in-place. If the reference count is greater than zero, then the
operation should (automatically) create a copy and then perform the
operation on the copy. Using this convention, for the sake of
efficiency all operations in Sage would be written to operate in-place
but they would transparently create copies of the object as necessary
in order to make side-effects impossible. Thus you can "have your cake
and eat it too".

Thus in

  newgraph=A.union(B).union(C).union(D).union(E)

would be done entirely in-place so that 'newgraph' becomes a modified
version of A, while in

  newgraph1=A.union(B).union(C).union(D).union(E)
  newgraph2=A.union(B).union(C).union(D).union(E)

a new copy of A is created and modified before it is assigned to
'newgraph2'. However we do not have to be aware of this as such. The
only thing we need to remember is that there can be no side-effects.

Regards,
Bill Page.

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-devel@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/sage-devel
URLs: http://sage.scipy.org/sage/ and http://modular.math.washington.edu/sage/
-~----------~----~----~----~------~----~------~--~---

Reply via email to