
Specific Statements
|
47
Generators and iterators
Functions containing a yield statement are compiled as
generators; when called, they return a generator object that
supports the iterator interface (i.e., a
next() method).
Iterators are objects returned by the
iter(X) built-in func-
tion; they define a
next() method, which returns the next
item in the iteration or raises a
StopIteration exception to
end the iteration.
Iteration contexts automatically use the iteration protocol to
step through collections. Classes can provide an
__iter__
method to overload the iter(X) built-in function call; if
defined, the result is used to step through objects in
for
loops, rather than the traditional __getitem__ indexing over-
load scheme.
The global Statement
global name [, name]*
The global statement is a namespace declaration: when used
inside a class or function, it treats appearances of
name as ref-
erences to a global (module-level) variable by that name—
whether it is assigned or not. Because of Python scope rules,
you need to declare only global names that are assigned
within a
def (global references are automatically found in the
enclosing module).
The import Statement
import module [, module]*
import [package.]* module [, [package.]* module]*
import [package.]* module as name [, [package.]*module as
name]*
The import statement provides module access: it imports a
module as a whole. Modules contain names fetched by quali- ...