Generator functions and user interfaces

Aaron "Castironpi" Brady castironpi at gmail.com
Wed Sep 10 15:19:56 EDT 2008


On Sep 10, 10:35 am, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> psaff... at googlemail.com a écrit :
>
> > I'm trying to implement an interactive graph visualisation tool using
> > matplotlib.
>
> > I want to use a spring layout, where nodes repulse each other and
> > edges act as springs to pull connected nodes together. Usually, this
> > algorithm runs through a number of iterations of attraction/repulsion
> > to allow the nodes to converge to suitable positions. However, rather
> > than running all these iterations to lay out the graph and then
> > rendering it, I want to animate the graph as it is "springing" into
> > place, and then allow the user to drag nodes around and have the graph
> > redraw on the fly.
>
> > My idea for doing this was to use a generator function, where I yield
> > the position of the nodes after each iteration and then call draw() on
> > the position yielded. Does this seem like a sensible approach?
>
> I don't have much experience with this kind of algorithms, but AFAICT,
> it seems sensible to me, yes. But don't take me on words...
>
> > The
> > problem is that the node positions that are being operated on by the
> > generator function may be altered by user input - dragging the nodes -
> > and I'm not sure if this will break the way that the new positions are
> > yielded. How do I use a generator function that might stop (when the
> > nodes stop moving) but then need to restart again (once the user moves
> > the nodes)?
>
> Starting with Python 2.5, there's a way to pass values back to generators:http://docs.python.org/whatsnew/pep-342.html
>
> Now, not having played much with these new features so far, I'm afraid I
> can't help more, nor even be strictly positive about this being what you
> need.
>
> Any generator guru around ?

Yield can return values.  The syntax you're looking for is:

def generator_fun( ):
   a= []
   while 1:
      b= yield( a )
      a.append( b )

g= generator_fun( )
g.next( )
g.send( 3 )
g.send( 4 )
g.send( 5 )

/Output:

>>> g.next( )
[]
>>> g.send( 3 )
[3]
>>> g.send( 4 )
[3, 4]
>>> g.send( 5 )
[3, 4, 5]

'g' is inactive in between 'send' calls.



More information about the Python-list mailing list