Subsections


3. Conventions

So that SAGE is easy to read, the goal is that the following style conventions are used for all code Python/Pyrex code that is included with SAGE.

Note: As of 2006-01-03 the code must be cleaned up further to obey these conventions. This is one of the main goals for SAGE 1.0.

3.1 File and directory names

Python SAGE library code uses the following conventions. Directory names may be plural (e.g., rings) and file names are almost always singular (e.g., polynomial_ring.py). Note that the file polynomial_ring.py might still contain definitions of several different types of polynomial rings.

Note: You are strongly encouraged to include miscellaneous notes, emails, design discussions, etc., in your package. Make these plain text files (with extension .txt) in a subdirectory directory called notes.

3.2 Except

Avoid whenever possible code like this:
try:
    some code
except:               # bad
    more code
Instead explicitly give the exceptions. For example,
try:
    return self.__coordinate_ring
except (AttributeError, other exceptions):           # Good
    more code to compute something
If you don't have any exceptions explicitly listed (as a tuple), your code will catch absolutely anything, including ctrl-C and alarms. This could be very confusing to users.


3.3 Docstrings

Every function should have a docstring that includes: Use the following template when documenting functions. Note the indentation:
def point(self, x=1, y=2):
    r"""           # note the r for "raw string"
    This function returns the point $(x^5,y)$.

    INPUT:
        self -- anything special about self
        x -- integer (default: 1) the ...
        y -- integer (default: 2) the ...

    OUTPUT:
        integer -- the ...

    EXAMPLES:
    This example illustrates ...
        sage: A = ModuliSpace()
        sage: A.point(2,3)
        xxx

    We now ...
        sage: B = A.point(5,6)
        sage: xxx

    It is an error to ...
        sage: C = A.point('x',7)
        Traceback (most recent call last):
        ...
        TypeError: unable to convert x (=r) to an integer

    AUTHOR: 
        - William Stein (2005-01-03)
    """
    <body of the function>
You are strongly encouraged to:

The code in the examples should pass automatic testing. This means that if the above code is in the file f.py (or f.sage), then sage -t f.py should not give any error messages. Testing occurs with full SAGE preparsing of input within the standard SAGE shell environment. Important. The file f.py is not imported when running tests unless you have arranged that it be imported into your SAGE environment, i.e., unless its functions are available when you start SAGE using the sage command.

3.3.1 Further conventions for automated testing of examples

The Python script local/bin/sage-doctest implements documentation testing in SAGE (see Chapter 4 for more details). When writing documentation, keep the following points in mind:

3.4 Optional packages

If an optional package is required for a certain function to work, that function should fail gracefully when the optional package is not available, and should give a hint about how to install it. For example, typing sage -optional gives a list of all optional packages, so suggest to the user that they type that.

3.5 Special SAGE methods

Just as Python has many standard special methods for objects, SAGE also has special methods. The are typically of the form _name_. (In a few cases the trailing underscore is not included, but I plan to change it so the trailing underscore is always included.) This section describes all special methods.

All objects in SAGE should derive from the Pyrex extension class SageObject:

from sage.ext.sage_object import SageObject

class MyClass(SageObject,...):
    ...

You should implement the _latex_ and _repn_ method for every object. The other methods depend on the nature of the object.

3.5.1 Latex representation

Every object x in SAGE should support the command latex(x), so that any SAGE objects can be easily and accurately displayed via LaTeX. Here is how to make an object support latex.
  1. Put import sage.misc.latex as latex at the top of the file that defines your class.
  2. Define a member function _latex_(self) that returns a LaTeX representation of your object. It should be something that can be typeset correctly within math mode.
  3. Often objects are built up out of other options. For example if c is a coefficient of your object, and you want to typeset c using latex, use latex(c) instead of c._latex_(), since c might not have a _latex_ method, and latex(c) knows how to deal with this.
  4. Don't forget to include a docstring and an example that illustrates latex generation for your object.
  5. You can use any macros included in amsmath, amssymb, amsfonts or defined in $SAGE_ROOT/doc/commontex/macros.tex.
  6. Use view(x) to view the typeset version of an object x.
import sage.misc.latex as latex
...
class X:
   ...
   def _latex_(self):
       """
       Return \Latex representation of X.
 
       EXAMPLES:
           sage: a = X(1,2)
           sage: latex(a)
           '\\frac{1}{2}'
       """
       return '\\frac{%s}{%s}''%(latex(self.numer), latex(self.denom))

3.5.2 Printing representation

The standard Python printing method is __repr__(self). In SAGE, that is for objects that derive from SageObject (which is everything in SAGE), instead define _repr_(self). This is preferable because if you only define _repr_(self) and not __repr__(self), then users can rename your object to print however they like.

3.5.3 Matrix from object

Provide a _matrix_ member function for any object that can be coerced to a matrix over a ring $ R$ . Then the SAGE function matrix will be implemented for your object.

3.5.4 Vector from object

Provide a _vector_ member function for any object that can be coerced to a vector over a ring $ R$ . Then the SAGE function vector will be implemented for your object.

3.6 Heading

The top of each SAGE code file should appear as follows:

r"""
<Very short 1-line summary>

<Paragraph description>
...

AUTHOR: 
    - YOUR NAME (2005-01-03): initial version
    - person (date in ISO year-month-day format): short desc
     ... 
    - person (date in ISO year-month-day format): short desc

\section{Tutorial}
 ...

Lots and lots of examples.
"""

#*****************************************************************************
#       Copyright (C) 2006 William Stein <wstein@gmail.com>
#                     2006 YOUR NAME <your email>
#
#  Distributed under the terms of the GNU General Public License (GPL)
#                  http://www.gnu.org/licenses/
#*****************************************************************************

All code included with SAGE must be licensed under the GPL or a less restrictive license (e.g., the BSD license). You should share copyright with me by including your name at the top. It is very important that you include your name in the AUTHOR log, since I want everybody who submits code to SAGE to receive proper credit. (If ever you feel you are not receiving proper credit for anything you submit to SAGE, please let me know!)

See About this document... for information on suggesting changes.