Sophie

Sophie

distrib > Mageia > 5 > i586 > by-pkgid > 27647990744ebd9cfe32398f37f67e20 > files > 2605

bzr-2.6.0-11.1.mga5.i586.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Bazaar Code Style Guide &mdash; Bazaar 2.6.0 documentation</title>
    
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    './',
        VERSION:     '2.6.0',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="shortcut icon" href="_static/bzr.ico"/>

    <link rel="top" title="Bazaar 2.6.0 documentation" href="index.html" />
    <link rel="next" title="Documenting Changes" href="documenting-changes.html" />
    <link rel="prev" title="Reviewing proposed changes to Bazaar" href="code-review.html" />
<link rel="stylesheet" href="_static/bzr-doc.css" type="text/css" />
 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="documenting-changes.html" title="Documenting Changes"
             accesskey="N">next</a></li>
        <li class="right" >
          <a href="code-review.html" title="Reviewing proposed changes to Bazaar"
             accesskey="P">previous</a> |</li>
<li><a href="http://bazaar.canonical.com/">
    <img src="_static/bzr icon 16.png" /> Home</a>&nbsp;|&nbsp;</li>
<a href="http://doc.bazaar.canonical.com/en/">Documentation</a>&nbsp;|&nbsp;</li>

        <li><a href="index.html">Developer Document Catalog (2.6.0)</a> &raquo;</li>
 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="bazaar-code-style-guide">
<h1>Bazaar Code Style Guide<a class="headerlink" href="#bazaar-code-style-guide" title="Permalink to this headline">¶</a></h1>
<div class="section" id="code-layout">
<h2>Code layout<a class="headerlink" href="#code-layout" title="Permalink to this headline">¶</a></h2>
<p>Please write <a class="reference external" href="http://www.python.org/peps/pep-0008.html">PEP-8</a> compliant code.</p>
<p>One often-missed requirement is that the first line of docstrings
should be a self-contained one-sentence summary.</p>
<p>We use 4 space indents for blocks, and never use tab characters.  (In vim,
<tt class="docutils literal"><span class="pre">set</span> <span class="pre">expandtab</span></tt>.)</p>
<p>Trailing white space should be avoided, but is allowed.
You should however not make lots of unrelated white space changes.</p>
<p>Unix style newlines (LF) are used.</p>
<p>Each file must have a newline at the end of it.</p>
<p>Lines should be no more than 79 characters if at all possible.
Lines that continue a long statement may be indented in either of
two ways:</p>
<p>within the parenthesis or other character that opens the block, e.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">my_long_method</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span>
               <span class="n">arg2</span><span class="p">,</span>
               <span class="n">arg3</span><span class="p">)</span>
</pre></div>
</div>
<p>or indented by four spaces:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">my_long_method</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span>
    <span class="n">arg2</span><span class="p">,</span>
    <span class="n">arg3</span><span class="p">)</span>
</pre></div>
</div>
<p>The first is considered clearer by some people; however it can be a bit
harder to maintain (e.g. when the method name changes), and it does not
work well if the relevant parenthesis is already far to the right.  Avoid
this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="bp">self</span><span class="o">.</span><span class="n">legbone</span><span class="o">.</span><span class="n">kneebone</span><span class="o">.</span><span class="n">shinbone</span><span class="o">.</span><span class="n">toebone</span><span class="o">.</span><span class="n">shake_it</span><span class="p">(</span><span class="n">one</span><span class="p">,</span>
                                                <span class="n">two</span><span class="p">,</span>
                                                <span class="n">three</span><span class="p">)</span>
</pre></div>
</div>
<p>but rather</p>
<div class="highlight-python"><div class="highlight"><pre><span class="bp">self</span><span class="o">.</span><span class="n">legbone</span><span class="o">.</span><span class="n">kneebone</span><span class="o">.</span><span class="n">shinbone</span><span class="o">.</span><span class="n">toebone</span><span class="o">.</span><span class="n">shake_it</span><span class="p">(</span><span class="n">one</span><span class="p">,</span>
    <span class="n">two</span><span class="p">,</span>
    <span class="n">three</span><span class="p">)</span>
</pre></div>
</div>
<p>or</p>
<div class="highlight-python"><div class="highlight"><pre><span class="bp">self</span><span class="o">.</span><span class="n">legbone</span><span class="o">.</span><span class="n">kneebone</span><span class="o">.</span><span class="n">shinbone</span><span class="o">.</span><span class="n">toebone</span><span class="o">.</span><span class="n">shake_it</span><span class="p">(</span>
    <span class="n">one</span><span class="p">,</span> <span class="n">two</span><span class="p">,</span> <span class="n">three</span><span class="p">)</span>
</pre></div>
</div>
<p>For long lists, we like to add a trailing comma and put the closing
character on the following line.  This makes it easier to add new items in
future:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">bzrlib.goo</span> <span class="kn">import</span> <span class="p">(</span>
    <span class="n">jam</span><span class="p">,</span>
    <span class="n">jelly</span><span class="p">,</span>
    <span class="n">marmalade</span><span class="p">,</span>
    <span class="p">)</span>
</pre></div>
</div>
<p>There should be spaces between function parameters, but not between the
keyword name and the value:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">call</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">cheese</span><span class="o">=</span><span class="n">quark</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="python-versions">
<h2>Python versions<a class="headerlink" href="#python-versions" title="Permalink to this headline">¶</a></h2>
<p>Bazaar supports Python from 2.6 through 2.7, and in the future we want to
support Python 3.  Avoid using language features added in
2.7, or features deprecated in Python 3.0.  (You can check v3
compatibility using the <tt class="docutils literal"><span class="pre">-3</span></tt> option of Python2.6.)</p>
</div>
<div class="section" id="hasattr-and-getattr">
<h2>hasattr and getattr<a class="headerlink" href="#hasattr-and-getattr" title="Permalink to this headline">¶</a></h2>
<p><tt class="docutils literal"><span class="pre">hasattr</span></tt> should not be used because it swallows exceptions including
<tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt>.  Instead, say something like</p>
<div class="highlight-python"><div class="highlight"><pre>if getattr(thing, &#39;name&#39;, None) is None
</pre></div>
</div>
</div>
<div class="section" id="kwargs">
<h2>kwargs<a class="headerlink" href="#kwargs" title="Permalink to this headline">¶</a></h2>
<p><tt class="docutils literal"><span class="pre">**kwargs</span></tt> in the prototype of a function should be used sparingly.
It can be good on higher-order functions that decorate other functions,
such as <tt class="docutils literal"><span class="pre">addCleanup</span></tt> or <tt class="docutils literal"><span class="pre">assertRaises</span></tt>, or on functions that take only
(or almost only) kwargs, where any kwargs can be passed.</p>
<p>Otherwise, be careful: if the parameters to a function are a bit complex
and might vary over time (e.g.  the <tt class="docutils literal"><span class="pre">commit</span></tt> API) then we prefer to pass an
object rather than a bag of positional and/or keyword args.  If you have
an arbitrary set of keys and values that are different with each use (e.g.
string interpolation inputs) then again that should not be mixed in with
the regular positional/keyword args, it seems like a different category of
thing.</p>
</div>
<div class="section" id="imitating-standard-objects">
<h2>Imitating standard objects<a class="headerlink" href="#imitating-standard-objects" title="Permalink to this headline">¶</a></h2>
<p>Don&#8217;t provide methods that imitate built-in classes (eg <tt class="docutils literal"><span class="pre">__in__</span></tt>,
<tt class="docutils literal"><span class="pre">__call__</span></tt>, <tt class="docutils literal"><span class="pre">__int__</span></tt>, <tt class="docutils literal"><span class="pre">__getitem__</span></tt>) unless the class you&#8217;re
implementing really does act like the builtin class, in semantics and
performance.</p>
<p>For example, old code lets you say <tt class="docutils literal"><span class="pre">file_id</span> <span class="pre">in</span> <span class="pre">inv</span></tt> but we no longer
consider this good style.  Instead, say more explicitly
<tt class="docutils literal"><span class="pre">inv.has_id(file_id)</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">__repr__</span></tt>, <tt class="docutils literal"><span class="pre">__cmp__</span></tt>, <tt class="docutils literal"><span class="pre">__str__</span></tt> are usually fine.</p>
</div>
<div class="section" id="module-imports">
<h2>Module Imports<a class="headerlink" href="#module-imports" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>Imports should be done at the top-level of the file, unless there is
a strong reason to have them lazily loaded when a particular
function runs.  Import statements have a cost, so try to make sure
they don&#8217;t run inside hot functions.</li>
<li>Module names should always be given fully-qualified,
i.e. <tt class="docutils literal"><span class="pre">bzrlib.hashcache</span></tt> not just <tt class="docutils literal"><span class="pre">hashcache</span></tt>.</li>
</ul>
</div>
<div class="section" id="naming">
<h2>Naming<a class="headerlink" href="#naming" title="Permalink to this headline">¶</a></h2>
<p>Functions, methods or members that are relatively private are given
a leading underscore prefix.  Names without a leading underscore are
public not just across modules but to programmers using bzrlib as an
API.</p>
<p>We prefer class names to be concatenated capital words (<tt class="docutils literal"><span class="pre">TestCase</span></tt>)
and variables, methods and functions to be lowercase words joined by
underscores (<tt class="docutils literal"><span class="pre">revision_id</span></tt>, <tt class="docutils literal"><span class="pre">get_revision</span></tt>).</p>
<p>For the purposes of naming some names are treated as single compound
words: &#8220;filename&#8221;, &#8220;revno&#8221;.</p>
<p>Consider naming classes as nouns and functions/methods as verbs.</p>
<p>Try to avoid using abbreviations in names, because there can be
inconsistency if other people use the full name.</p>
</div>
<div class="section" id="standard-names">
<h2>Standard Names<a class="headerlink" href="#standard-names" title="Permalink to this headline">¶</a></h2>
<p><tt class="docutils literal"><span class="pre">revision_id</span></tt> not <tt class="docutils literal"><span class="pre">rev_id</span></tt> or <tt class="docutils literal"><span class="pre">revid</span></tt></p>
<p>Functions that transform one thing to another should be named <tt class="docutils literal"><span class="pre">x_to_y</span></tt>
(not <tt class="docutils literal"><span class="pre">x2y</span></tt> as occurs in some old code.)</p>
</div>
<div class="section" id="destructors">
<h2>Destructors<a class="headerlink" href="#destructors" title="Permalink to this headline">¶</a></h2>
<p>Python destructors (<tt class="docutils literal"><span class="pre">__del__</span></tt>) work differently to those of other
languages.  In particular, bear in mind that destructors may be called
immediately when the object apparently becomes unreferenced, or at some
later time, or possibly never at all.  Therefore we have restrictions on
what can be done inside them.</p>
<ol class="arabic simple" start="0">
<li>If you think you need to use a <tt class="docutils literal"><span class="pre">__del__</span></tt> method ask another
developer for alternatives.  If you do need to use one, explain
why in a comment.</li>
<li>Never rely on a <tt class="docutils literal"><span class="pre">__del__</span></tt> method running.  If there is code that
must run, instead have a <tt class="docutils literal"><span class="pre">finally</span></tt> block or an <tt class="docutils literal"><span class="pre">addCleanup</span></tt> call an
explicit <tt class="docutils literal"><span class="pre">close</span></tt> method.</li>
<li>Never <tt class="docutils literal"><span class="pre">import</span></tt> from inside a <tt class="docutils literal"><span class="pre">__del__</span></tt> method, or you may crash the
interpreter!!</li>
<li>Prior to bzr 2.4, we sometimes used to raise warnings from del methods
that the object was not cleaned up or closed.  We no longer do this:
failure to close the object doesn&#8217;t cause a test failure; the warning
appears an arbitrary long time after the problem occurred (the object
being leaked); merely having a del method inhibits Python gc; the
warnings appear to users and upset them; they can also break tests that
are checking what appears on stderr.</li>
</ol>
<p>In short, just don&#8217;t use <tt class="docutils literal"><span class="pre">__del__</span></tt>.</p>
</div>
<div class="section" id="cleanup-methods">
<h2>Cleanup methods<a class="headerlink" href="#cleanup-methods" title="Permalink to this headline">¶</a></h2>
<p>Often when something has failed later code will fail too, including
cleanups invoked from <tt class="docutils literal"><span class="pre">finally</span></tt> blocks.  These secondary failures are
generally uninteresting compared to the original exception.  <tt class="docutils literal"><span class="pre">bzrlib</span></tt>
has some facilities you can use to mitigate this.</p>
<ul>
<li><p class="first">In <tt class="docutils literal"><span class="pre">Command</span></tt> subclasses, prefer the <tt class="docutils literal"><span class="pre">add_cleanup</span></tt> method to using
<tt class="docutils literal"><span class="pre">try</span></tt>/<tt class="docutils literal"><span class="pre">finally</span></tt> blocks.  E.g. to acquire a lock and ensure it will
always be released when the command is done:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="bp">self</span><span class="o">.</span><span class="n">add_cleanup</span><span class="p">(</span><span class="n">branch</span><span class="o">.</span><span class="n">lock_read</span><span class="p">()</span><span class="o">.</span><span class="n">unlock</span><span class="p">)</span>
</pre></div>
</div>
<p>This also avoids heavily indented code. It also makes it easier to notice
mismatched lock/unlock pairs (and other kinds of resource
acquire/release) because there isn&#8217;t a large block of code separating
them.</p>
</li>
<li><p class="first">Use the <tt class="docutils literal"><span class="pre">only_raises</span></tt> decorator (from <tt class="docutils literal"><span class="pre">bzrlib.decorators</span></tt>) when
defining methods that are typically called in <tt class="docutils literal"><span class="pre">finally</span></tt> blocks, such
as <tt class="docutils literal"><span class="pre">unlock</span></tt> methods.  For example, <tt class="docutils literal"><span class="pre">&#64;only_raises(LockNotHeld,</span>
<span class="pre">LockBroken)</span></tt>.  All errors that are unlikely to be a knock-on failure
from a previous failure should be allowed.</p>
</li>
<li><p class="first">Consider using the <tt class="docutils literal"><span class="pre">OperationWithCleanups</span></tt> helper from
<tt class="docutils literal"><span class="pre">bzrlib.cleanup</span></tt> anywhere else you have a <tt class="docutils literal"><span class="pre">finally</span></tt> block that
might fail.</p>
</li>
</ul>
</div>
<div class="section" id="factories">
<h2>Factories<a class="headerlink" href="#factories" title="Permalink to this headline">¶</a></h2>
<p>In some places we have variables which point to callables that construct
new instances.  That is to say, they can be used a lot like class objects,
but they shouldn&#8217;t be <em>named</em> like classes.  Things called <tt class="docutils literal"><span class="pre">FooBar</span></tt> should
create an instance of <tt class="docutils literal"><span class="pre">FooBar</span></tt>.  A factory method that might create a
<tt class="docutils literal"><span class="pre">FooBar</span></tt> or might make something else should be called <tt class="docutils literal"><span class="pre">foo_factory</span></tt>.</p>
</div>
<div class="section" id="registries">
<h2>Registries<a class="headerlink" href="#registries" title="Permalink to this headline">¶</a></h2>
<p>Several places in Bazaar use (or will use) a registry, which is a
mapping from names to objects or classes.  The registry allows for
loading in registered code only when it&#8217;s needed, and keeping
associated information such as a help string or description.</p>
</div>
<div class="section" id="interobject-and-multiple-dispatch">
<h2>InterObject and multiple dispatch<a class="headerlink" href="#interobject-and-multiple-dispatch" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">InterObject</span></tt> provides for two-way <a class="reference external" href="http://en.wikipedia.org/wiki/Multiple_dispatch">multiple dispatch</a>: matching
up for example a source and destination repository to find the right way
to transfer data between them.</p>
<p>There is a subclass <tt class="docutils literal"><span class="pre">InterObject</span></tt> classes for each type of object that is
dispatched this way, e.g. <tt class="docutils literal"><span class="pre">InterRepository</span></tt>.  Calling <tt class="docutils literal"><span class="pre">.get()</span></tt> on this
class will return an <tt class="docutils literal"><span class="pre">InterObject</span></tt> instance providing the best match for
those parameters, and this instance then has methods for operations
between the objects.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">inter</span> <span class="o">=</span> <span class="n">InterRepository</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">source_repo</span><span class="p">,</span> <span class="n">target_repo</span><span class="p">)</span>
<span class="n">inter</span><span class="o">.</span><span class="n">fetch</span><span class="p">(</span><span class="n">revision_id</span><span class="p">)</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">InterRepository</span></tt> also acts as a registry-like object for its
subclasses, and they can be added through <tt class="docutils literal"><span class="pre">.register_optimizer</span></tt>.  The
right one to run is selected by asking each class, in reverse order of
registration, whether it <tt class="docutils literal"><span class="pre">.is_compatible</span></tt> with the relevant objects.</p>
</div>
<div class="section" id="lazy-imports">
<h2>Lazy Imports<a class="headerlink" href="#lazy-imports" title="Permalink to this headline">¶</a></h2>
<p>To make startup time faster, we use the <tt class="docutils literal"><span class="pre">bzrlib.lazy_import</span></tt> module to
delay importing modules until they are actually used. <tt class="docutils literal"><span class="pre">lazy_import</span></tt> uses
the same syntax as regular python imports. So to import a few modules in a
lazy fashion do:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">bzrlib.lazy_import</span> <span class="kn">import</span> <span class="n">lazy_import</span>
<span class="n">lazy_import</span><span class="p">(</span><span class="nb">globals</span><span class="p">(),</span> <span class="s">&quot;&quot;&quot;</span>
<span class="s">import os</span>
<span class="s">import subprocess</span>
<span class="s">import sys</span>
<span class="s">import time</span>

<span class="s">from bzrlib import (</span>
<span class="s">   errors,</span>
<span class="s">   transport,</span>
<span class="s">   revision as _mod_revision,</span>
<span class="s">   )</span>
<span class="s">import bzrlib.transport</span>
<span class="s">import bzrlib.xml5</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>At this point, all of these exist as a <tt class="docutils literal"><span class="pre">ImportReplacer</span></tt> object, ready to
be imported once a member is accessed. Also, when importing a module into
the local namespace, which is likely to clash with variable names, it is
recommended to prefix it as <tt class="docutils literal"><span class="pre">_mod_&lt;module&gt;</span></tt>. This makes it clearer that
the variable is a module, and these object should be hidden anyway, since
they shouldn&#8217;t be imported into other namespaces.</p>
<p>While it is possible for <tt class="docutils literal"><span class="pre">lazy_import()</span></tt> to import members of a module
when using the <tt class="docutils literal"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">member</span></tt> syntax, it is recommended to
only use that syntax to load sub modules <tt class="docutils literal"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">submodule</span></tt>.
This is because variables and classes can frequently be used without
needing a sub-member for example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">lazy_import</span><span class="p">(</span><span class="nb">globals</span><span class="p">(),</span> <span class="s">&quot;&quot;&quot;</span>
<span class="s">from module import MyClass</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">MyClass</span><span class="p">)</span>
</pre></div>
</div>
<p>This will incorrectly fail, because <tt class="docutils literal"><span class="pre">MyClass</span></tt> is a <tt class="docutils literal"><span class="pre">ImportReplacer</span></tt>
object, rather than the real class.</p>
<p>It also is incorrect to assign <tt class="docutils literal"><span class="pre">ImportReplacer</span></tt> objects to other variables.
Because the replacer only knows about the original name, it is unable to
replace other variables. The <tt class="docutils literal"><span class="pre">ImportReplacer</span></tt> class will raise an
<tt class="docutils literal"><span class="pre">IllegalUseOfScopeReplacer</span></tt> exception if it can figure out that this
happened. But it requires accessing a member more than once from the new
variable, so some bugs are not detected right away.</p>
</div>
<div class="section" id="the-null-revision">
<h2>The Null revision<a class="headerlink" href="#the-null-revision" title="Permalink to this headline">¶</a></h2>
<p>The null revision is the ancestor of all revisions.  Its revno is 0, its
revision-id is <tt class="docutils literal"><span class="pre">null:</span></tt>, and its tree is the empty tree.  When referring
to the null revision, please use <tt class="docutils literal"><span class="pre">bzrlib.revision.NULL_REVISION</span></tt>.  Old
code sometimes uses <tt class="docutils literal"><span class="pre">None</span></tt> for the null revision, but this practice is
being phased out.</p>
</div>
<div class="section" id="object-string-representations">
<h2>Object string representations<a class="headerlink" href="#object-string-representations" title="Permalink to this headline">¶</a></h2>
<p>Python prints objects using their <tt class="docutils literal"><span class="pre">__repr__</span></tt> method when they are
written to logs, exception tracebacks, or the debugger.  We want
objects to have useful representations to help in determining what went
wrong.</p>
<p>If you add a new class you should generally add a <tt class="docutils literal"><span class="pre">__repr__</span></tt> method
unless there is an adequate method in a parent class.  There should be a
test for the repr.</p>
<p>Representations should typically look like Python constructor syntax, but
they don&#8217;t need to include every value in the object and they don&#8217;t need
to be able to actually execute.  They&#8217;re to be read by humans, not
machines.  Don&#8217;t hardcode the classname in the format, so that we get the
correct value if the method is inherited by a subclass.  If you&#8217;re
printing attributes of the object, including strings, you should normally
use <tt class="docutils literal"><span class="pre">%r</span></tt> syntax (to call their repr in turn).</p>
<p>Try to avoid the representation becoming more than one or two lines long.
(But balance this against including useful information, and simplicity of
implementation.)</p>
<p>Because repr methods are often called when something has already gone
wrong, they should be written somewhat more defensively than most code.
They shouldn&#8217;t have side effects like doing network or disk
IO.
The object may be half-initialized or in some other way in an illegal
state.  The repr method shouldn&#8217;t raise an exception, or it may hide the
(probably more useful) underlying exception.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s">(</span><span class="si">%r</span><span class="s">)&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span>
                       <span class="bp">self</span><span class="o">.</span><span class="n">_transport</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="exception-handling">
<h2>Exception handling<a class="headerlink" href="#exception-handling" title="Permalink to this headline">¶</a></h2>
<p>A bare <tt class="docutils literal"><span class="pre">except</span></tt> statement will catch all exceptions, including ones that
really should terminate the program such as <tt class="docutils literal"><span class="pre">MemoryError</span></tt> and
<tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt>.  They should rarely be used unless the exception is
later re-raised.  Even then, think about whether catching just
<tt class="docutils literal"><span class="pre">Exception</span></tt> (which excludes system errors in Python2.5 and later) would
be better.</p>
<p>The <tt class="docutils literal"><span class="pre">__str__</span></tt> method on exceptions should be small and have no side
effects, following the rules given for <a class="reference internal" href="#object-string-representations">Object string representations</a>.
In particular it should not do any network IO, or complicated
introspection of other objects.  All the state needed to present the
exception to the user should be gathered before the error is raised.
In other words, exceptions should basically be value objects.</p>
</div>
<div class="section" id="test-coverage">
<h2>Test coverage<a class="headerlink" href="#test-coverage" title="Permalink to this headline">¶</a></h2>
<p>All code should be exercised by the test suite.  See the <a class="reference external" href="http://doc.bazaar.canonical.com/developers/testing.html">Bazaar Testing
Guide</a> for detailed
information about writing tests.</p>
</div>
<div class="section" id="assertions">
<h2>Assertions<a class="headerlink" href="#assertions" title="Permalink to this headline">¶</a></h2>
<p>Do not use the Python <tt class="docutils literal"><span class="pre">assert</span></tt> statement, either in tests or elsewhere.
A source test checks that it is not used.  It is ok to explicitly raise
AssertionError.</p>
<p>Rationale:</p>
<ul class="simple">
<li>It makes the behaviour vary depending on whether bzr is run with -O
or not, therefore giving a chance for bugs that occur in one case or
the other, several of which have already occurred: assertions with
side effects, code which can&#8217;t continue unless the assertion passes,
cases where we should give the user a proper message rather than an
assertion failure.</li>
<li>It&#8217;s not that much shorter than an explicit if/raise.</li>
<li>It tends to lead to fuzzy thinking about whether the check is
actually needed or not, and whether it&#8217;s an internal error or not</li>
<li>It tends to cause look-before-you-leap patterns.</li>
<li>It&#8217;s unsafe if the check is needed to protect the integrity of the
user&#8217;s data.</li>
<li>It tends to give poor messages since the developer can get by with
no explanatory text at all.</li>
<li>We can&#8217;t rely on people always running with -O in normal use, so we
can&#8217;t use it for tests that are actually expensive.</li>
<li>Expensive checks that help developers are better turned on from the
test suite or a -D flag.</li>
<li>If used instead of <tt class="docutils literal"><span class="pre">self.assert*()</span></tt> in tests it makes them falsely
pass with -O.</li>
</ul>
</div>
<div class="section" id="emacs-setup">
<h2>emacs setup<a class="headerlink" href="#emacs-setup" title="Permalink to this headline">¶</a></h2>
<p>In emacs:</p>
<div class="highlight-python"><div class="highlight"><pre>;(defface my-invalid-face
;  &#39;((t (:background &quot;Red&quot; :underline t)))
;  &quot;Face used to highlight invalid constructs or other uglyties&quot;
;  )

(defun my-python-mode-hook ()
 ;; setup preferred indentation style.
 (setq fill-column 79)
 (setq indent-tabs-mode nil) ; no tabs, never, I will not repeat
;  (font-lock-add-keywords &#39;python-mode
;                         &#39;((&quot;^\\s *\t&quot; . &#39;my-invalid-face) ; Leading tabs
;                            (&quot;[ \t]+$&quot; . &#39;my-invalid-face)  ; Trailing spaces
;                            (&quot;^[ \t]+$&quot; . &#39;my-invalid-face)); Spaces only
;                          )
 )

(add-hook &#39;python-mode-hook &#39;my-python-mode-hook)
</pre></div>
</div>
<p>The lines beginning with &#8216;;&#8217; are comments. They can be activated
if one want to have a strong notice of some tab/space usage
violations.</p>
</div>
<div class="section" id="portability-tips">
<h2>Portability Tips<a class="headerlink" href="#portability-tips" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">bzrlib.osutils</span></tt> module has many useful helper functions, including
some more portable variants of functions in the standard library.</p>
<p>In particular, don&#8217;t use <tt class="docutils literal"><span class="pre">shutil.rmtree</span></tt> unless it&#8217;s acceptable for it
to fail on Windows if some files are readonly or still open elsewhere.
Use <tt class="docutils literal"><span class="pre">bzrlib.osutils.rmtree</span></tt> instead.</p>
<p>Using the <tt class="docutils literal"><span class="pre">open(..).read(..)</span></tt> or <tt class="docutils literal"><span class="pre">open(..).write(..)</span></tt> style chaining
of methods for reading or writing file content relies on garbage collection
to close the file which may keep the file open for an undefined period of
time. This may break some follow up operations like rename on Windows.
Use <tt class="docutils literal"><span class="pre">try/finally</span></tt> to explictly close the file. E.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;foo.txt&#39;</span><span class="p">,</span> <span class="s">&#39;w&#39;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="terminology">
<h2>Terminology<a class="headerlink" href="#terminology" title="Permalink to this headline">¶</a></h2>
<p>Bazaar is a GNU project and uses standard GNU terminology, especially:</p>
<blockquote>
<div><ul class="simple">
<li>Use the word &#8220;Linux&#8221; to refer to the Linux kernel, not as a synechoche
for the entire operating system.  (See <a class="reference external" href="https://bugs.launchpad.net/bzr/+bug/528253">bug 528253</a>).</li>
<li>Don&#8217;t say &#8220;open source&#8221; when you mean &#8220;free software&#8221;.</li>
</ul>
</div></blockquote>
</div>
<div class="section" id="dynamic-imports">
<h2>Dynamic imports<a class="headerlink" href="#dynamic-imports" title="Permalink to this headline">¶</a></h2>
<p>If you need to import a module (or attribute of a module) named in a
variable:</p>
<blockquote>
<div><ul class="simple">
<li>If importing a module, not an attribute, and the module is a top-level
module (i.e. has no dots in the name), then it&#8217;s ok to use the builtin
<tt class="docutils literal"><span class="pre">__import__</span></tt>, e.g. <tt class="docutils literal"><span class="pre">__import__(module_name)</span></tt>.</li>
<li>In all other cases, prefer <tt class="docutils literal"><span class="pre">bzrlib.pyutils.get_named_object</span></tt> to the
built-in <tt class="docutils literal"><span class="pre">__import__</span></tt>.  <tt class="docutils literal"><span class="pre">__import__</span></tt> has some subtleties and
unintuitive behaviours that make it hard to use correctly.</li>
</ul>
</div></blockquote>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="index.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Bazaar Code Style Guide</a><ul>
<li><a class="reference internal" href="#code-layout">Code layout</a></li>
<li><a class="reference internal" href="#python-versions">Python versions</a></li>
<li><a class="reference internal" href="#hasattr-and-getattr">hasattr and getattr</a></li>
<li><a class="reference internal" href="#kwargs">kwargs</a></li>
<li><a class="reference internal" href="#imitating-standard-objects">Imitating standard objects</a></li>
<li><a class="reference internal" href="#module-imports">Module Imports</a></li>
<li><a class="reference internal" href="#naming">Naming</a></li>
<li><a class="reference internal" href="#standard-names">Standard Names</a></li>
<li><a class="reference internal" href="#destructors">Destructors</a></li>
<li><a class="reference internal" href="#cleanup-methods">Cleanup methods</a></li>
<li><a class="reference internal" href="#factories">Factories</a></li>
<li><a class="reference internal" href="#registries">Registries</a></li>
<li><a class="reference internal" href="#interobject-and-multiple-dispatch">InterObject and multiple dispatch</a></li>
<li><a class="reference internal" href="#lazy-imports">Lazy Imports</a></li>
<li><a class="reference internal" href="#the-null-revision">The Null revision</a></li>
<li><a class="reference internal" href="#object-string-representations">Object string representations</a></li>
<li><a class="reference internal" href="#exception-handling">Exception handling</a></li>
<li><a class="reference internal" href="#test-coverage">Test coverage</a></li>
<li><a class="reference internal" href="#assertions">Assertions</a></li>
<li><a class="reference internal" href="#emacs-setup">emacs setup</a></li>
<li><a class="reference internal" href="#portability-tips">Portability Tips</a></li>
<li><a class="reference internal" href="#terminology">Terminology</a></li>
<li><a class="reference internal" href="#dynamic-imports">Dynamic imports</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="code-review.html"
                        title="previous chapter">Reviewing proposed changes to Bazaar</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="documenting-changes.html"
                        title="next chapter">Documenting Changes</a></p>
  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="_sources/code-style.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="documenting-changes.html" title="Documenting Changes"
             >next</a></li>
        <li class="right" >
          <a href="code-review.html" title="Reviewing proposed changes to Bazaar"
             >previous</a> |</li>
<li><a href="http://bazaar.canonical.com/">
    <img src="_static/bzr icon 16.png" /> Home</a>&nbsp;|&nbsp;</li>
<a href="http://doc.bazaar.canonical.com/en/">Documentation</a>&nbsp;|&nbsp;</li>

        <li><a href="index.html">Developer Document Catalog (2.6.0)</a> &raquo;</li>
 
      </ul>
    </div>
    <div class="footer">
        &copy; Copyright 2009-2011 Canonical Ltd.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.3.
    </div>
  </body>
</html>