Review of Expert Python Programming, Part Two

Chapter 3
Subclassing Built-in Types
  • I started learning Python after this was added, so it never occurred to me not to do this.
Accessing Methods from Superclasses
  • Tries to explain super, but it's quite confusing (mostly due to the multiple-inheritance problems).
  • The standard docs do a better job of making it clear the main benefit is making maintenance easier in single-inheritance examples.
Understanding Python's Method Resolution Order (MRO)
The section isn't as clear as it could be, but it has solid information. It explains what the MRO is used for and how it's different between 2.2 and 2.3, and the __mro__ attribute
super Pitfalls
Points out some of the most common problems with super: mixing super and classic calls (and how to use __mro__ to choose what to do) and subclass constructors that take arguments that differ from their parent classes.
Best Practices
  • Solid, short (so you can remember it) section.
Descriptors and Properties
This section isn't overly clear. It describes what descriptors are from a technical perspective, but doesn't do a great job of explaining why you'd want to use them. Also, a fair number of the examples have errors, e.g., code for setting values when the text says it is for reading values. Luckily, it contains a link to the (more helpful) How-To Guide for Descriptors.
This section explains property and the property attributes it returns (though not necessarily why they're so useful) and does a good job of pointing out some gotchas, e.g., the way they don't pick up overridden methods. The solution offered is perfectly sensible: override the property instead of the (typically private) method bound to fget.
  • Short but informative section on slots, which I haven't seen mentioned before.
The __new__ Method
This section covers __new__ and its usefulness for making sure that a class's invariants aren't violated because a subclass didn't explicitly invoke __init__.
The __metaclass__ method
This section covers customizing class creation using __metaclass__ and points out that, in most cases, there are easier-to-understand alternatives. One example of when there isn't is adjusting read-only attributes, e.g., the __doc__ attribute of the built-in metaclass type. Other suggested usages for __metaclass__ include frameworks enforcing behavior across large groups of classes and orthogonal functionality such as logging. The section closes with a link to A Primer on Python Metaclass Programming.

The summary section is a short, bulleted list highlighting the most important points made in the chapter. Again, it's short enough to be easily memorable.

Back to flipping out...

blog comments powered by Disqus