[Tutor] Python best practices
Lie Ryan
lie.1296 at gmail.com
Sat Nov 28 19:26:30 CET 2009
On 11/27/2009 7:03 PM, Stefan Lesicnik wrote:
> hihi! (two in 1 day!)
>
> Is there a document, pep, wiki etc that defines best practice for python code? (maybe its more generic).
PEP 8 is the official style guideline.
> I keep stumbling on things I think, it would be nice if someone mentioned this. Some things ive seen
>
> - keep you try blocks as small as possible, so you can isolate the error
> - functions should return one value (im not 100% of this one)
I 100% disagree or with this one.
> - declare variable names in a certain way (place?)
> - use the if __name__ == '__main__': main() convention
Python specific best practices, among the most important ones are:
- use new-style classes (derive from object)
- avoid "for x in range(len(list)):", when you need the index prefer
enumerate
- if you can think of a functionality, it is very likely it exist
somewhere in the stdlib or at least it exists as a 3rd party lib
http://xkcd.com/353/
- @property and attributes over getter and setter
- don't assume the use a reference counting GC, close file properly or
use with block
- ''.join() when building large string
- don't manipulate path names, use os.path
- when writing GUI program, IDLE may mess things up
More general non-python-specific:
- write unittest for any serious code, preferrably write unittest before
writing code
- it's easier to optimize correct code, than the correct optimized code
- when using nested loop (implicit or explicit), be wary of possible
quadratic (or worse) behavior.
More information about the Tutor
mailing list