Edit March 14, 2014: Fix conditional in Composed Method section. Thanks Rufus Smith.
Edit February 28, 2014:
NotImplemented to avoid asymmetric comparison. Thanks Daniel Smith.
Edit February 28, 2014: Removed
enumerate usage in "Interesting Return Value" section. Thanks Hugh Brown and Paul Winkler.
Edit September 5, 2013: Fixed error in Sorted Collection. Thanks Frank Sievertsen.
Edit September 4, 2013: Fixed typo in Choosing Message gist.
instanceof() should be
isinstance(). Thanks to
richardborcsik for catching this.
Edit July 30, 2013: Fixed typo in Sorted Collection gist.
__lt__(self, other) needs two arguments. Thanks to Tiago Oliveira for catching this.
These are my notes from Vladimir Keleshev's talk entitled "Python Best Practice Patterns", given on May 2, 2013 at the Python Meetup in Denmark. The original video is here (about 38 minutes long).
NOTE: Some of the code examples have been has been modified from the original presentation based on readers' feedback (see edits above).
NOTE: As Keleshev points out in the video, the code examples are written for Python 3, so all classes are new-style, even if they do not explicitly subclass from
- Divide program into methods that perform one task
- Keep all operation in a method at the same level of abstraction
Use many methods only a few lines long
Different levels of abstraction: bitmaps, filesystem operations, playing sounds...
safety_checkdeals with temp and pressure
alarmdeals with files and sound
pressuredeals with bits and converting them
- provide constructors that create well-formed instances
- Pass all required parameters to them
- Can use class methods to make multiple constructors
- Example: Using Cartesian or polar coordinates
- How do you code a method where many lines of code share many arguments and temporary variables?
- Can't be solved by making many small methods (would use more code)
Execute around method (in Python: Context manager)
- How do you represent pairs of actions that should be taken together?
Debug printing method
__repr__for debugging/interactive mode
- small methods can be more effective than comments
Intention revealing message
- How do you communicate your intent when implementation is simple?
- Use for methods that do the same thing (for readability)
Constant method (constant class variable)
- Depends if you are designing to make your class subclassable
Direct and indirect variable access
- no need for getters and setters
Enumeration (iteration) method
- Can often use sets instead of combination of
- Probably the only case to check
Simple enumeration parameter
- When you can't come up with an iteration param that makes sense, just use
- Instead of writing methods without return values, make them return self
- allows cascading of methods
Interesting return value
- Explicit better than implicit
- Include return value if it's interesting (even if it's
- Smalltalk Best Practice Patterns
- Not just for Smalltalk: applicable to Python, Ruby, and many other languages