Generator Frustration
Joel
joel.welling at gmail.com
Mon Jun 20 18:04:36 EDT 2011
On Jun 4, 2:27 pm, "TommyVee" <xxxxx... at xxxxxx.xxx> wrote:
> I'm using the SimPy package to run simulations. Anyone who's used this
> package knows that the way it simulates process concurrency is through the
> clever use of yield statements. Some of the code in my programs is very
> complex and contains several repeating sequences of yield statements. I
> want to combine these sequences into common functions. The problem of
> course, is that once a yield gets put into a function, the function is now a
> generator and its behavior changes. Is there any elegant way to do this? I
> suppose I can do things like ping-pong yield statements, but that solutions
> seems even uglier than having a very flat, single main routine with
> repeating sequences.
>
> Thanks in advance.
I actually found a reasonable answer to this, I think. If one of the
called functions contains a yield, that function is by definition a
generator, and will test as such with 'if
type(result)==types.GeneratorType:'. This makes it possible for the
function that calls the subroutine to either do its own yield, or to
yield the result of the function's next 'yield' statement. I've got a
class the run method of which calls the 'cycle' method of its derived
class, as follows:
while True:
result= self.cycle(now()) # result may or may not be a
generator
if type(result)==types.GeneratorType:
# Next is a generator, meaning it includes a
'yield'.
# Otherwise, result should be None and cycle is a
simple
# function.
try:
yield result.next()
while True:
yield result.next()
except StopIteration:
pass
else:
# self.cycle() was a simple function, returning None-
it's
# done now.
pass
# It is time for this process to go back to sleep; all the
yields
# in self.cycle() have been processed.
yield hold,self,self.nextCycleTime-now()
More information about the Python-list
mailing list