[Twisted-Python] A Python metaclass for Twisted allowing __init__ to return a Deferred

Terry Jones terry at jon.es
Sun Nov 2 20:01:08 EST 2008

Hi Tristan

>>>>> "Tristan" == Tristan Seligmann <mithrandi at mithrandi.net> writes:
Tristan> You can, however, encapsulate it into a classmethod or free
Tristan> function that you call to get an instance of MyClass. This is a
Tristan> pattern often seen when there are various ways to build an
Tristan> instance of some class; you'll have a very basic __init__, and
Tristan> then a bunch of factory functions or classmethods that do more
Tristan> complicated work before passing the results in to the class's
Tristan> constructor.

OK, thanks.

It feels to me (please correct me if I'm wrong) that the main reason you'd
want to follow this pattern is because you can't deal with Deferreds in an
__init__ method.

If you weren't dealing with Deferreds, you could just pass args to __init__
and have it figure out what to do. While it might be simpler to do as you
describe, and have various external factories, it feels (to me anyway) like
you're taking behavior that's class-dependent and putting it outside the

__init__ can't return a result, presumably because if it has something it
wants to remember, or give you access to, it can put it on self, provide
you with a method, etc.

But in the Twisted world, I think it makes sense that there is some
provision for what's essentially a two-phase __init__.  I quite like my
approach, because the programmer wanting to write "normal" Twisted code
will likely find it natural that __init__ could work with Deferreds,
including returning one. To me that feels very natural.

Having said that, I don't particularly like the fact that there's a
special-case metaclass creating my classes, even though I wrote the code
myself :-)

>> BTW, I sometimes have the feeling that Deferreds are like how M$
>> characterizes the GPL. Viral. Once you call anything creating a Deferred,
>> you're hooked - whatcha gonna do with that Deferred boy? Take one sip of
>> the Deferred Kool Aid and the next thing you know you're on a drip.

Tristan> Just wait until you start trying to combine iterators and deferreds ;)

Oh yeah... I tried that too :-)


Comments on that code very welcome too!


More information about the Twisted-Python mailing list