[Twisted-web] Old Style python classes in Twisted

Glyph glyph at twistedmatrix.com
Sun Oct 7 04:33:36 EDT 2012


On Oct 6, 2012, at 2:50 PM, exarkun at twistedmatrix.com wrote:

> On 09:22 pm, ardesai at yahoo.com wrote:
>> Given that twisted tutorials and other written materials show examples 
>> of derived classes for Protocol, HTTP Request etc., is there a good 
>> reason for many classes (almost all I suspect) (e.g. 'class Request' , 
>> 'class BaseProtocol',  'class _PauseableMixin', etc.) to be old style 
>> classes as opposed to a new style python classes?
>> 
>> Given that newer versions of twisted (and user apps) run on newer 
>> versions of python, I initially (a few years ago) tried to call the 
>> base class using super(), but was surprised to find twisted implements 
>> using old style classes.
>> 
>> 
>> New style classes make it easy to call a base class method (by using 
>> super).  Would the MRO in new style classes make it better or worse? 
>> However, nothing wrong with old style classes, esp. if twisted depends 
>> on the depth-first MRO of old style classes.
>> 
>> Can someone clarify whether use of old style classes is intentional 
>> (e.g. due to MRO)?
> 
> It is intentional in case any applications based on Twisted rely on 
> behavior of classic classes, such as the MRO differences.  Classes added 
> to Twisted now are all new-style, though.

In your own applications, if you want to call the base class using super(), in most cases you may simply do this:

class MyNewStyleThing(OldStyleThingFromTwisted, object):

Sticking 'object' on the end of the inheritance hierarchy is always[1] safe; it will make your new class new-style, and it will keep working if you ever manage to migrate to Python 3, where all classes are new-style; or, if Twisted ever undergoes a "flag day" to switch over to new-style classes for everything.

(Warning: sticking 'object' on the front of your inheritance hierarchy will rarely appear to work, but it will almost always cause weird issues and can easily fail later.  Remember to put it on the end.)

This inspired me to write a new ticket, <http://twistedmatrix.com/trac/ticket/6076>, in case anyone would at least like to prevent the type-distinction infection from becoming worse over time.

Good luck,

-glyph

[1]: by which I mean, of course, "almost always".  Caveat coder.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-web/attachments/20121007/2daf95e1/attachment.htm 


More information about the Twisted-web mailing list