Python norms
The python community shares not only the language and standard library, but also various community norms, such as the Style Guide for Python Code (PEP 8).
For example, the use of 4-space indentation, and no tabs, is not my idea, though I like it. --DanC 14:52, 4 September 2009 (UTC)
Contents |
Idioms
The following is a quick index by idiom.
main()
if __name__ == '__main__': main(sys.argv)
This test passes when the module is used as a script as in:
$ python foo.py
as opposed to a module as in
import foo
See:
- 6.1.1. Executing modules as scripts in the python tutorial.
- Python main() functions by Guido van van Rossum May 15, 2003 in All Things Pythonic
Doctest
def trim_allele(allele, digits):
'''
>>> trim_allele('DRA*010201', 4)
'DRA*0102'
>>> trim_allele('DRA*0101', 2)
'DRA*01'
'''
gene, allele = allele.split("*")
return "%s*%s" % (gene, allele[:digits])
...
def _test():
import doctest
doctest.testmod()
This is using the extremely nifty doctest module:
The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.
A local convention laid on top is the use of a --test command line argument to invoke the tests rather than the normal use of the script.
.doctest files
The doctest mode walkthru shows how to use doctest mode in emacs; where previously I would manually test and debug designs, leaving no tangible results, using .doctest files allows me to capture the results in a combination of design notes and automated tests.
You can run the tests a la:
$ python -m doctest -v resnums.doctest
You can simultaneously follow the in reStructuredText conventions and get hypertext documentation out of the same .doctest file a la:
$ rst2html resnums.doctest >resnums.html
@@ISSUE: where to put the resulting .html files? check them into SVN?
Internal functions
def _internal():
A leading underscore is a convention for an internal-use-only function.
Tips and Tools
- Python sidebar for the Mozilla family of web browser
Open Issues
- importing modules across directories
- especially from pdb/templates/pdb_tpl.py
- I use PYTHONPATH, but I can't believe that's best current practice. I've read a little on this issue but don't fully grok yet.
- using the python debugger in emacs: I know this can be done, but I haven't researched how. I currently just use it from a shell window.
