Python Best Practice Patterns by Vladimir Keleshev (Notes)
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.
- 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
March 14, 2014: Fix conditional in Composed Method section. Thanks Rufus Smith.
February 28, 2014:
NotImplemented to avoid asymmetric comparison. Thanks Daniel Smith.
February 28, 2014: Removed
enumerate usage in "Interesting Return Value" section. Thanks Hugh Brown and Paul Winkler.
September 5, 2013: Fixed error in Sorted Collection. Thanks Frank Sievertsen.
September 4, 2013: Fixed typo in Choosing Message gist.
instanceof() should be
isinstance(). Thanks to
richardborcsik for catching this.
July 30, 2013: Fixed typo in Sorted Collection gist.
__lt__(self, other) needs two arguments. Thanks to Tiago Oliveira for catching this.
Please send comments by email. I welcome your feedback, advice, and criticism.