[Twisted-Python] Sequential use of asynchronous calls

Ben Artin ben at artins.org
Sat May 26 23:45:14 EDT 2007


> Since it is used as a decorator, the @sequential line will be  
> written by the
> same person who wrote the function itself. If the author of the  
> function
> knows it is not a generator, why would he apply @sequential (or
> @inlineCallbacks) to it?

One reason is that if the function returns None, then if you require  
it to be a generator, you have to add a gratuitous "yield None" just  
to shut up the piece of code that requires a generator. For example:

@sequential
def foo():
	blah = blah

would cause the error, but

@sequential
def foo():
	blah = blah
	yield None

would not. In my opinion, that "yield None" is just noise, and  
doesn't make the code any better, faster, safer, or easier to read,  
so given the option I would make @sequential cope even when yield  
None is not there.


The other main case where I've run into this is when you have a  
protocol that expects some method to behave according to @sequential,  
but a particular implementation of that protocol doesn't need to do  
more than immediately return. For example:

class TakesALongTime():
	@sequential
	def doSomething(self):
		yield doPart1()
		yield doPart2()
		yield someResult


class ReturnsImmediately():
	@sequential
	def doSomething(self):
		return someResult


Now, if you use "return" in the first class, you get a syntax error  
right away, because a non-empty return in a generator is a syntax  
error. On the other hand, if you use "return" in the second class,  
you don't get a syntax error, but your implementation of @sequential  
would produce a runtime error. I understand why it's easy to produce  
that runtime error, but I don't see any benefit to it -- it doesn't  
really save the users of @sequential any effort.

> But should it be given any interpretation at all? Unless there is a  
> real use
> case for it, I think it's better to consider it an error.

I would agree with you if I thought there was any possibility that  
interpreting a plain function as a generator with a single yield  
could yield unintended results, but I have yet to find such a case.

Ben

--

<http://artins.org/ben>

"The last great thing written in C was Franz Schubert's Symphony  
number 9."






More information about the Twisted-Python mailing list