passing parameters to generators ?

Jan Samohyl asgard at hellnet.cz
Mon Nov 5 08:59:12 EST 2001


On Mon, Nov 05, 2001 at 07:48:29PM +1000, Joal Heagney wrote:
> Emile van Sebille wrote:
> 
> > This came up earlier this week.  Here's my response to the earlier question:
> > 
> > You can share mutable objects to pass in information:
> > 
> > def gf(args):
> >     while 1:
> >         yield args[0]*args[1]
> > 
> > a = [2,3]
> > g = gf(a)
> > print g.next()
> > a[1]=4
> > print g.next()
> > 
> > Is this what you're looking for?
> 
> Yow! Emile, how on earth did you discover this, or should I read the PEP
> a little more thoroughly?

There is really nothing strange in it: a is just a reference to mutable object, so changing it changes for the generator.
It has nothing to do with the generator stuff. The same trick can be used for passing variable default parameters. 

Regards, Jan Samohyl




More information about the Python-list mailing list