[Twisted-Python] Not subclassing internet.TCPServer
glyph at divmod.com
glyph at divmod.com
Fri Aug 25 14:20:53 EDT 2006
On Thu, 24 Aug 2006 14:30:48 -0400, "Chaz." <eprparadocs at gmail.com> wrote:
>So my question is why is subclassing internet.TCPServer not a good idea?
In the general case, the short version is: "Because we wrote that code, and we say so."
Usually I am not a big fan of the "argument from authority", but in this case, it has a special significance. When a developer on a library you're using says "this is the correct, supported method to use interface XYZ", that means that is the method they are going to be supporting in the future, and unsupported usages may break. It is in your best interest to stick to the supported usage if you ever intend to upgrade that library.
In a future version of twisted.internet.application, for example, it may be deemed a good idea to make TCPServer and friends a set of functions rather than classes for some reason. Since you're supposed to be calling them and not subclassing them, that usage will continue to work, but subclassing won't.
Calling is generally better than subclassing anyway. When you subclass, a number of undesirable things happen: in any language with multiple inheritance this is a problem, but in Python especially, you inherit all sorts of things from your superclass other than simple functionality.
For one thing, object semantics. Maybe you used to be a classic class, but subclassing turns you into a new-style class before you're ready to make that switch. Maybe your superclass has a bizarre metaclass which performs some mutation you didn't expect. Maybe it has a __new__ which does something weird.
Then you inherit state. Your 'self.' namespace becomes polluted with additional variable names that may conflict with your own. These names may change in future releases, so even if they don't conflict now, they may in future releases.
While inheritance can be a useful tool, it is a lot more complex than composition, so you should generally avoid it unless all these ugly side-effects are actually desirable properties in your particular application. In the case of twisted.application.internet, they are not. That's not to say they *never* are: default implementation classes paired with interfaces can insulate your applications from certain varieties of change in libraries, and sometimes all those object-model features described as annoyances above are incredibly useful (most usually in persistence libraries like Axiom or ZODB).
More information about the Twisted-Python