270
295
<http://doc.bazaar-vcs.org/developers/overview.html>`_.
273
Coding Style Guidelines
274
#######################
279
``hasattr`` should not be used because it swallows exceptions including
280
``KeyboardInterrupt``. Instead, say something like ::
282
if getattr(thing, 'name', None) is None
288
Please write PEP-8__ compliant code.
290
__ http://www.python.org/peps/pep-0008.html
292
One often-missed requirement is that the first line of docstrings
293
should be a self-contained one-sentence summary.
295
We use 4 space indents for blocks, and never use tab characters. (In vim,
298
Trailing white space should be avoided, but is allowed.
299
You should however not make lots of unrelated white space changes.
301
Unix style newlines (LF) are used.
303
Each file must have a newline at the end of it.
305
Lines should be no more than 79 characters if at all possible.
306
Lines that continue a long statement may be indented in either of
309
within the parenthesis or other character that opens the block, e.g.::
315
or indented by four spaces::
321
The first is considered clearer by some people; however it can be a bit
322
harder to maintain (e.g. when the method name changes), and it does not
323
work well if the relevant parenthesis is already far to the right. Avoid
326
self.legbone.kneebone.shinbone.toebone.shake_it(one,
332
self.legbone.kneebone.shinbone.toebone.shake_it(one,
338
self.legbone.kneebone.shinbone.toebone.shake_it(
341
For long lists, we like to add a trailing comma and put the closing
342
character on the following line. This makes it easier to add new items in
345
from bzrlib.goo import (
351
There should be spaces between function parameters, but not between the
352
keyword name and the value::
354
call(1, 3, cheese=quark)
358
;(defface my-invalid-face
359
; '((t (:background "Red" :underline t)))
360
; "Face used to highlight invalid constructs or other uglyties"
363
(defun my-python-mode-hook ()
364
;; setup preferred indentation style.
365
(setq fill-column 79)
366
(setq indent-tabs-mode nil) ; no tabs, never, I will not repeat
367
; (font-lock-add-keywords 'python-mode
368
; '(("^\\s *\t" . 'my-invalid-face) ; Leading tabs
369
; ("[ \t]+$" . 'my-invalid-face) ; Trailing spaces
370
; ("^[ \t]+$" . 'my-invalid-face)); Spaces only
374
(add-hook 'python-mode-hook 'my-python-mode-hook)
376
The lines beginning with ';' are comments. They can be activated
377
if one want to have a strong notice of some tab/space usage
384
* Imports should be done at the top-level of the file, unless there is
385
a strong reason to have them lazily loaded when a particular
386
function runs. Import statements have a cost, so try to make sure
387
they don't run inside hot functions.
389
* Module names should always be given fully-qualified,
390
i.e. ``bzrlib.hashcache`` not just ``hashcache``.
396
Functions, methods or members that are relatively private are given
397
a leading underscore prefix. Names without a leading underscore are
398
public not just across modules but to programmers using bzrlib as an
401
We prefer class names to be concatenated capital words (``TestCase``)
402
and variables, methods and functions to be lowercase words joined by
403
underscores (``revision_id``, ``get_revision``).
405
For the purposes of naming some names are treated as single compound
406
words: "filename", "revno".
408
Consider naming classes as nouns and functions/methods as verbs.
410
Try to avoid using abbreviations in names, because there can be
411
inconsistency if other people use the full name.
417
``revision_id`` not ``rev_id`` or ``revid``
419
Functions that transform one thing to another should be named ``x_to_y``
420
(not ``x2y`` as occurs in some old code.)
426
Python destructors (``__del__``) work differently to those of other
427
languages. In particular, bear in mind that destructors may be called
428
immediately when the object apparently becomes unreferenced, or at some
429
later time, or possibly never at all. Therefore we have restrictions on
430
what can be done inside them.
432
0. If you think you need to use a ``__del__`` method ask another
433
developer for alternatives. If you do need to use one, explain
436
1. Never rely on a ``__del__`` method running. If there is code that
437
must run, do it from a ``finally`` block instead.
439
2. Never ``import`` from inside a ``__del__`` method, or you may crash the
442
3. In some places we raise a warning from the destructor if the object
443
has not been cleaned up or closed. This is considered OK: the warning
444
may not catch every case but it's still useful sometimes.
450
Often when something has failed later code, including cleanups invoked
451
from ``finally`` blocks, will fail too. These secondary failures are
452
generally uninteresting compared to the original exception. So use the
453
``only_raises`` decorator (from ``bzrlib.decorators``) for methods that
454
are typically called in ``finally`` blocks, such as ``unlock`` methods.
455
For example, ``@only_raises(LockNotHeld, LockBroken)``. All errors that
456
are unlikely to be a knock-on failure from a previous failure should be
463
In some places we have variables which point to callables that construct
464
new instances. That is to say, they can be used a lot like class objects,
465
but they shouldn't be *named* like classes::
467
> I think that things named FooBar should create instances of FooBar when
468
> called. Its plain confusing for them to do otherwise. When we have
469
> something that is going to be used as a class - that is, checked for via
470
> isinstance or other such idioms, them I would call it foo_class, so that
471
> it is clear that a callable is not sufficient. If it is only used as a
472
> factory, then yes, foo_factory is what I would use.
478
Several places in Bazaar use (or will use) a registry, which is a
479
mapping from names to objects or classes. The registry allows for
480
loading in registered code only when it's needed, and keeping
481
associated information such as a help string or description.
484
InterObject and multiple dispatch
485
=================================
487
The ``InterObject`` provides for two-way `multiple dispatch`__: matching
488
up for example a source and destination repository to find the right way
489
to transfer data between them.
491
.. __: http://en.wikipedia.org/wiki/Multiple_dispatch
493
There is a subclass ``InterObject`` classes for each type of object that is
494
dispatched this way, e.g. ``InterRepository``. Calling ``.get()`` on this
495
class will return an ``InterObject`` instance providing the best match for
496
those parameters, and this instance then has methods for operations
501
inter = InterRepository.get(source_repo, target_repo)
502
inter.fetch(revision_id)
504
``InterRepository`` also acts as a registry-like object for its
505
subclasses, and they can be added through ``.register_optimizer``. The
506
right one to run is selected by asking each class, in reverse order of
507
registration, whether it ``.is_compatible`` with the relevant objects.
512
To make startup time faster, we use the ``bzrlib.lazy_import`` module to
513
delay importing modules until they are actually used. ``lazy_import`` uses
514
the same syntax as regular python imports. So to import a few modules in a
517
from bzrlib.lazy_import import lazy_import
518
lazy_import(globals(), """
527
revision as _mod_revision,
529
import bzrlib.transport
533
At this point, all of these exist as a ``ImportReplacer`` object, ready to
534
be imported once a member is accessed. Also, when importing a module into
535
the local namespace, which is likely to clash with variable names, it is
536
recommended to prefix it as ``_mod_<module>``. This makes it clearer that
537
the variable is a module, and these object should be hidden anyway, since
538
they shouldn't be imported into other namespaces.
540
While it is possible for ``lazy_import()`` to import members of a module
541
when using the ``from module import member`` syntax, it is recommended to
542
only use that syntax to load sub modules ``from module import submodule``.
543
This is because variables and classes can frequently be used without
544
needing a sub-member for example::
546
lazy_import(globals(), """
547
from module import MyClass
551
return isinstance(x, MyClass)
553
This will incorrectly fail, because ``MyClass`` is a ``ImportReplacer``
554
object, rather than the real class.
556
It also is incorrect to assign ``ImportReplacer`` objects to other variables.
557
Because the replacer only knows about the original name, it is unable to
558
replace other variables. The ``ImportReplacer`` class will raise an
559
``IllegalUseOfScopeReplacer`` exception if it can figure out that this
560
happened. But it requires accessing a member more than once from the new
561
variable, so some bugs are not detected right away.
567
The null revision is the ancestor of all revisions. Its revno is 0, its
568
revision-id is ``null:``, and its tree is the empty tree. When referring
569
to the null revision, please use ``bzrlib.revision.NULL_REVISION``. Old
570
code sometimes uses ``None`` for the null revision, but this practice is
574
Object string representations
575
=============================
577
Python prints objects using their ``__repr__`` method when they are
578
written to logs, exception tracebacks, or the debugger. We want
579
objects to have useful representations to help in determining what went
582
If you add a new class you should generally add a ``__repr__`` method
583
unless there is an adequate method in a parent class. There should be a
586
Representations should typically look like Python constructor syntax, but
587
they don't need to include every value in the object and they don't need
588
to be able to actually execute. They're to be read by humans, not
589
machines. Don't hardcode the classname in the format, so that we get the
590
correct value if the method is inherited by a subclass. If you're
591
printing attributes of the object, including strings, you should normally
592
use ``%r`` syntax (to call their repr in turn).
594
Try to avoid the representation becoming more than one or two lines long.
595
(But balance this against including useful information, and simplicity of
598
Because repr methods are often called when something has already gone
599
wrong, they should be written somewhat more defensively than most code.
600
The object may be half-initialized or in some other way in an illegal
601
state. The repr method shouldn't raise an exception, or it may hide the
602
(probably more useful) underlying exception.
607
return '%s(%r)' % (self.__class__.__name__,
614
A bare ``except`` statement will catch all exceptions, including ones that
615
really should terminate the program such as ``MemoryError`` and
616
``KeyboardInterrupt``. They should rarely be used unless the exception is
617
later re-raised. Even then, think about whether catching just
618
``Exception`` (which excludes system errors in Python2.5 and later) would
625
All code should be exercised by the test suite. See the `Bazaar Testing
626
Guide <http://doc.bazaar-vcs.org/developers/testing.html>`_ for detailed
627
information about writing tests.