Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Defining a Generator

The presence of the yield statement in a function means that the function is actually a generator object, and will have the an iterator-like interface built automatically. In effect it becomes a stateful object with a next method defined — so it will work with the for statement — and it will raise the StopIteration exception when it returns.

The syntax for a function definition is in the section called “Function Definition: The def and return Statements”; a generator is similar.

def name ( 〈 parameter ...〉 ): suite

The suite of statements must include at least one yield statement.

The yield statement specifies the values emitted by the generator. Note that the expression is required.

yield expression

If the return statement is used, it ends the generator, and raises the StopIteration exception to alert the for statement. For obvious reasons, the return statement cannot return a value.

Here's a complete, but silly example of a generator.

def primes():
    yield 2
    yield 3
    yield 5
    yield 7
    yield 11
    return

In this case, we simply yield a fixed sequence of values. After yielding five values, it exits. Here's how this generator is used by a for statement.

>>> 
for p in primes():
...     print p



2
3
5
7
11

 
 
  Published under the terms of the Open Publication License Design by Interspire