[Twisted-Python] deferred object inside function
robert at gravina.com
Fri Jul 7 05:24:14 EDT 2006
> Yusnel Rojas García wrote:
>> how can I make a function which have a deferred object return a
>> value that
>> depends of the deferred object's result.
>> how can get the result from the resolver?
>> from twisted.names import client, dns
>> def somefunction(somepars):
>> r = client.Resolver('/etc/resolv.conf')
>> d = r.resolve(dns.Query('www.example.com', dns.MX, dns.IN))
>> d.Callbacks(somefunct1, somefunctErr2)
>> return ?
> Have you read the docs on deferreds? There's a bunch of good ones now,
> and you can get to them here:
Yes, I think http://twistedmatrix.com/projects/core/documentation/
howto/defer.html is a good place to start also.
While I'm no Twisted expert, I think the main point of confusion you
are having is here:
The great thing about Deferreds (and Twisted) is that it is
asynchronous - that means that calls like your DNS query are non-
blocking - in other words, your program doesn't sit around and wait
while the DNS query is happening. I think you are expecting your
program to wait until the DNS query is finished before getting to the
"return" line... but it will keep on going, and later (at some time,
maybe a few seconds later) either your "somefunct1" will be called if
everything worked out, or your "somefunctErr2" will be called if
there is an error. But, it will get to the return line probably
before either of those two methods get called.
I really do suggest working through the Twisted Howtos (they are
*excellent*) and running the example code to see it in action. It
helps a lot.
> In particular, you want the section on "Low-Level Networking and Event
> In your example above, you probably want this, instead:
> d.addCallbacks(yourCallback, yourErrback)
> As for your question, see if this sums it up:
> * You want some data
> * The data depends upon the result
> If that's correct, then you can only get your data in the callback.
> Think about writing a class to handle this, and instead of having a
> function return what you want, you could set a class attribute with
> data you're looking for once the callback is fired. Or any other of
> hundreds of possible solutions ;-)
> Twisted-Python mailing list
> Twisted-Python at twistedmatrix.com
More information about the Twisted-Python