edit it down, remove some bits that are not likely to come up for most programmers

[Imported from Trac: page CodingStandards, version 2]
zooko 2009-05-17 00:29:39 +00:00
parent b4e89b273c
commit a5a15063ea

@ -5,7 +5,7 @@ Here are some Python code style guidelines. We also include official Python guid
## basic standards ## basic standards
### compatibility ### compatibility
Tahoe requires Python v2.4 or greater. No effort should be made to offer compatibility with versions of Python older than 2.4. Effort should be made to work with the most recent release of Python v2.x, and with every release between v2.4 and the most recent release. Tahoe requires Python v2.4.2 or greater. No effort should be made to offer compatibility with versions of Python older than 2.4.2. Effort should be made to work with the most recent release of Python v2.x, and with every release between v2.4.2 and the most recent 2.x.
### naming and layout ### naming and layout
@ -37,63 +37,12 @@ from amdlib.util.assertutil import _assert, precondition, postcondition
### truths and falsehoods ### truths and falsehoods
* Always use `True` or `False` if that is what you mean -- never write a literal `0`, `1`, or `None` to indicate a boolean value. * Don't use the literals `True` or `False` in conditional expressions -- instead just write the expression which will evaluate to true or false. For example, write `if expr:` instead of `if expr == True:` and `if not expr:` instead of `if expr == False:`.
* Never use the literals `True` or `False` in conditional expressions -- instead just write the expression which will evaluate to true or false. For example, write `if expr:` instead of `if expr == True:` and `if not expr:` instead of `if expr == False:`.
* Use the fact that empty sequences, empty strings, empty dicts, `0`, and `None` all evaluate to false. Write `if not items:` instead of `if len(items) == 0:`. * Use the fact that empty sequences, empty strings, empty dicts, `0`, and `None` all evaluate to false. Write `if not items:` instead of `if len(items) == 0:`.
* But if your intent is to test for `None` instead of to test for "any false thing", then write it out as `if thing is None:`. * But if your intent is to test for `None` instead of to test for "any false thing", then write it out as `if thing is None:`.
## advanced idioms ## advanced idioms
### assertion policy
One axis of interest is how time-consuming the checks are. Many precondition
checks can cause typical runtime to explode to O(n^2^) or O(n^3^), for example
`SortedList.__contains__` called `_assert_invariants` which took
O(n log n) each time, when `__contains__` ought to be O(log n). A caller who
was expecting `if b in list` to take O(log n) could easily wind up turning
their O(n log n) routine into O(n^2^) or worse.
Another axis is "who could cause it to fail": some checks are looking only at
internal state. For example, if `SortedList._assert_invariants` fails, it
indicates a problem in some `SortedList` method. Other checks are
enforcing the external API, like those which do typechecks on input
arguments. Even after the `SortedList` developer has gained confidence in
the code and decides that internal checks are no longer necessary, it may be
useful to retain the external checks to isolate usage problems that exist in
callers.
We decided upon a couple of policies for the future:
* The general rule is that nodes must be functional for light traffic even
when the assertions are turned on. When assertions are turned off (-O),
nodes must be functional for heavy traffic.
* Time-consuming internal checks: once the code is working properly,
consider removing them, but they may be left in place as long as they
use `assert` (the form which gets turned off when -O is used).
* Cheap internal checks: once the code is working properly, consider
removing them, but it is less of a concern than the time-consuming ones.
If they really are cheap, use `_assert` (the unconditional form
that gets used even with -O).
* Time-consuming external checks: maybe leave them in place, but always
use `assert` so they will not be used with -O.
* Cheap external checks: leave them in place, using the unconditional
`_assert`
* Production grids could run with -O (in practice, the allmydata.com production grid runs without -O, because there are no expensive checks in the current codebase).
* Testing grids might run without -O in order to detect more bugs.
* Local developer tests will probably not use -O, and developers should be
prepared to experience the same CPU load problems if they subject their
nodes to real traffic levels. Developers can use -O to turn off everyone
else's checks, use `_assert` on their own code to enable their own
assertions, and then subject their nodes to heavy traffic, as long as they
are sure to change their checks to use `assert` (or remove them
altogether) before committing.
### preconditions and assertions ### preconditions and assertions
@ -142,15 +91,65 @@ def _assert_consistency(self):
Now you can put `assert self._assert_consistency()` everywhere in your class where the class ought to be in an internally consistent state. For example, at the beginning of every externally-callable method. This technique can be very valuable in developing a complex class -- it catches bugs early, it isolates bugs into specific code paths, and it clarifies the internal structure of the class so that other developers can hack on it without subtle misunderstandings. Now you can put `assert self._assert_consistency()` everywhere in your class where the class ought to be in an internally consistent state. For example, at the beginning of every externally-callable method. This technique can be very valuable in developing a complex class -- it catches bugs early, it isolates bugs into specific code paths, and it clarifies the internal structure of the class so that other developers can hack on it without subtle misunderstandings.
=== configuration === ==== assertion policy ====
==== minimizing configuration ==== One axis of interest is how time-consuming the checks are. Many precondition
checks can cause typical runtime to explode to O(n^2^) or O(n^3^), for example
`SortedList.__contains__` called `_assert_invariants` which took
O(n log n) each time, when `__contains__` ought to be O(log n). A caller who
was expecting `if b in list` to take O(log n) could easily wind up turning
their O(n log n) routine into O(n^2^) or worse.
Another axis is "who could cause it to fail": some checks are looking only at
internal state. For example, if `SortedList._assert_invariants` fails, it
indicates a problem in some `SortedList` method. Other checks are
enforcing the external API, like those which do typechecks on input
arguments. Even after the `SortedList` developer has gained confidence in
the code and decides that internal checks are no longer necessary, it may be
useful to retain the external checks to isolate usage problems that exist in
callers.
* The general rule is that nodes must be functional for light traffic even
when the assertions are turned on. When assertions are turned off (-O),
nodes must be functional for heavy traffic.
* Time-consuming internal checks: once the code is working properly,
consider removing them, but they may be left in place as long as they
use `assert` (the form which gets turned off when -O is used).
* Cheap internal checks: once the code is working properly, consider
removing them, but it is less of a concern than the time-consuming ones.
If they really are cheap, use `_assert` (the unconditional form
that gets used even with -O).
* Time-consuming external checks: maybe leave them in place, but always
use `assert` so they will not be used with -O.
* Cheap external checks: leave them in place, using the unconditional
`_assert`
* Production grids could run with -O (in practice, the allmydata.com production grid runs without -O, because there are no expensive checks in the current codebase).
* Testing grids might run without -O in order to detect more bugs.
* Local developer tests will probably not use -O, and developers should be
prepared to experience the same CPU load problems if they subject their
nodes to real traffic levels. Developers can use -O to turn off everyone
else's checks, use `_assert` on their own code to enable their own
assertions, and then subject their nodes to heavy traffic, as long as they
are sure to change their checks to use `assert` (or remove them
altogether) before committing.
### configuration
#### minimizing configuration
* Do not implement configuration files for modules or libraries -- code that is going to be used by other code. Only applications -- code that is going to be used by humans -- have configuration files. Modules and libraries get "configured" by the code that calls them, for example by passing arguments to their constructors. * Do not implement configuration files for modules or libraries -- code that is going to be used by other code. Only applications -- code that is going to be used by humans -- have configuration files. Modules and libraries get "configured" by the code that calls them, for example by passing arguments to their constructors.
* If there are constant values which end-users do not need to modify, then do not make them configurable, but put them in all-caps variables at the beginning of the Python file in which they are used. * If there are constant values which end-users do not need to modify, then do not make them configurable, but put them in all-caps variables at the beginning of the Python file in which they are used.
* Design algorithms so that they have as few "voodoo constants" and "tweakable parameters" as possible. If you find yourself needing to add more and more special cases to handle failures of the basic algorithm, this might indicate that the basic algorithm ought to be replaced with one that doesn't have so many edge cases. * Design algorithms so that they have as few "voodoo constants" and "tweakable parameters" as possible.
==== how to implement configuration ==== #### how to implement configuration
Whether in application code or in library code, never pass configuration values via a configuration object. Instead use Python parameters. For example -- here's another real-life example -- do not write Whether in application code or in library code, never pass configuration values via a configuration object. Instead use Python parameters. For example -- here's another real-life example -- do not write
@ -164,8 +163,6 @@ class BlockStore:
self.basepath = os.path.abspath(confdict.get("PATH", "")) self.basepath = os.path.abspath(confdict.get("PATH", ""))
self.maintainertype = confdict.get("MAINTAINER", "rnd").lower() self.maintainertype = confdict.get("MAINTAINER", "rnd").lower()
self.backendtype = confdict.get("BACKEND", "flat").lower() self.backendtype = confdict.get("BACKEND", "flat").lower()
blockstore = BlockStore(confdict)
``` ```
, but instead write , but instead write
@ -176,21 +173,9 @@ class BlockStore:
self.basepath = os.path.abspath(path) self.basepath = os.path.abspath(path)
self.maintainertype = maintainertype self.maintainertype = maintainertype
self.backendtype = backendtype self.backendtype = backendtype
maxspace = confdict.get('MAX_MEGABYTES')
if maxspace is not None:
maxspace = int(maxspace) * 2**20
blockstore = BlockStore(maxspace, confdict.get('PATH', ""), confdict.get('MAINTAINER', 'rnd').lower(), confdict.get('BACKEND', 'flat').lower())
``` ```
. .
## Twisted gotchas
The standard-library os.popen() function is not compatible with the way Twisted uses SIGCHLD. The usual symptom is that a read() or readlines() on the filehandle returned by
os.popen() fails with EINTR "Interrupted System Call". I'm not sure exactly why this happens, and worse yet it only happens intermittently (-warner 06-Dec-2005).
Instead of os.popen(), you should use twisted.internet.utils.getProcessOutput(). This function returns a Deferred which fires (with the contents of stdout) when the process
completes. This means, of course, that you must attach a callback to handle the output, rather than blocking the entire process while you wait for a synchronous result.
## official Python standards ## official Python standards