Generator state/parameters

David Mertz, Ph.D. mertz at gnosis.cx
Thu Dec 11 14:23:34 EST 2003


|Robin Becker <robin at jessikat.fsnet.co.uk> writes:
|> I was just about to ask if generators allow for a stream like mechanism,
|> but obviously if we're not allowed to change the generator state then it
|> seems quite hard.

Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote previously:
|Well, there's always global state.

But the state need not be global, just a mutable object yielded by a
generator.  As I thought about this fact, I have come to find Raymond
Hettinger's proposals for enhancing simple generators less urgent (but I
probably still vote +1, though now moot).

  >>> def echo():
  ...     message = [None]
  ...     while message[0] != "EXIT":
  ...         yield message
  ...
  >>> for mess in echo():
  ...     if mess[0] is not None: print mess[0]
  ...     mess[0] = raw_input("Word: ")
  ...
  Word: foo
  foo
  Word: bar
  bar
  Word: EXIT

This is a toy example, but the point is that we are perfectly able to
pass data back into a generator without using global state.

--
---[ to our friends at TLAs (spread the word) ]--------------------------
Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego
White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad
---[ Postmodern Enterprises <mertz at gnosis.cx> ]--------------------------






More information about the Python-list mailing list