Style
Style: main elements
-
Use 4 spaces per indent, rather than tabs.
-
Use blank lines before function defs, and to separate logical code units.
-
function_names; variable_names; keyword_named_variables_; ClassNames; modname; CONSTANT_NAMES
-
Keep lines to 79 characters or less.
aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaa
-
Spaces around operators and after commas, but not just inside (){}[]:
a = (1, 2)
-
Indent comments to the level of the code referred to.
Documentation
-
Docstrings are automatically extracted to describe your code.
-
They are triple-double quote enclosed comments after, for example, function declarations.
-
For some peculiar reason, they are written as commands not descriptions
def add(num1, num2):
"""Add two numbers."""
- Example
def add (num1, num2):
"""
Add two numbers.
Keyword arguments:
num1 -- an integer or double number (no default)
num2 -- an integer or double number (no default)
Returns:
The sum of the numbers.
"""
return num1 + num2
-
Style details:
https://www.python.org/dev/peps/pep-0257/
PyDoc
-
PyDoc is the documentation system distributed with Python.
-
Best way to invoke it is to import any code, and then type:
>>> help(x)
Where "x" is a function, module, dotted object method etc.
-
If you want to see docstrings, then:
print(function_name.__doc__)
Other software
DocTest
-
DocTest runs short tests built into your documentation.
"""
Add two numbers together.
>>> add(1,2)
3
"""
def add (num1, num2):
return num1 + num2
DocTest
Write a test class
-
This will make more sense after we look at classes:
# test.py
import unittest
import docs
class TestDocs(unittest.TestCase):
def test_add(self):
self.assertEqual(docs.add(1,2), 3)
if __name__ == '__main__':
unittest.main()
Write a test class
-
Run it:
python tests.py
-
Or verbose:
python -m unittest -v tests.py
-
In the latter case you can delete the:
if __name__ == '__main__':
unittest.main()