Good set of slides: http://python.net/~goodger/projects/pycon/2007/idiomatic/presentation.html
python -c "import this"
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
https://www.python.org/dev/peps/pep-0008/
-
Python probably has a module for it e.g.
- Don't write/read xml/json etc yourself. See https://docs.python.org/2/library/markup.html
- Use
os.path
over adding slashes yourself
-
The
unittest
module is used for unit testing- A new object is created for each test method
- Use __class__ for single instance setup, e.g. https://github.com/mantidproject/mantid/blob/master/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunTest.py
- We still need to support python 2.6 so check the documentation for all of the supported assert methods.
-
Know the difference between
_
and__
prefixes_
informally marks an attribute as internal. Not imported when doingfrom module import *
__
mangles the name with the class name so that only class methods can access the attributes. This also disables overloading so use it with caution!- Never name you own methods with double underscores at the start and end. These should be reserved for Python itself.
- Good examples: http://igorsobreira.com/2010/09/16/difference-between-one-underline-and-two-underlines-in-python.html
-
Classes without any other base class should inherit from object
-
Use
string.join
instead of+=
colors = ['red', 'blue', 'green', 'yellow']
Don't do this:
result = ''
for s in colors:
result += s
Instead, do this:
result = ''.join(colors)
- Use
is None
and never== None