blob: 2eb86e29e1a9d8616f704675217c4396035d64e7 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001.. _tut-classes:
2
3*******
4Classes
5*******
6
7Python's class mechanism adds classes to the language with a minimum of new
8syntax and semantics. It is a mixture of the class mechanisms found in C++ and
9Modula-3. As is true for modules, classes in Python do not put an absolute
10barrier between definition and user, but rather rely on the politeness of the
11user not to "break into the definition." The most important features of classes
12are retained with full power, however: the class inheritance mechanism allows
13multiple base classes, a derived class can override any methods of its base
14class or classes, and a method can call the method of a base class with the same
15name. Objects can contain an arbitrary amount of private data.
16
17In C++ terminology, all class members (including the data members) are *public*,
18and all member functions are *virtual*. There are no special constructors or
19destructors. As in Modula-3, there are no shorthands for referencing the
20object's members from its methods: the method function is declared with an
21explicit first argument representing the object, which is provided implicitly by
22the call. As in Smalltalk, classes themselves are objects, albeit in the wider
23sense of the word: in Python, all data types are objects. This provides
24semantics for importing and renaming. Unlike C++ and Modula-3, built-in types
25can be used as base classes for extension by the user. Also, like in C++ but
26unlike in Modula-3, most built-in operators with special syntax (arithmetic
27operators, subscripting etc.) can be redefined for class instances.
28
29
30.. _tut-terminology:
31
32A Word About Terminology
33========================
34
35Lacking universally accepted terminology to talk about classes, I will make
36occasional use of Smalltalk and C++ terms. (I would use Modula-3 terms, since
37its object-oriented semantics are closer to those of Python than C++, but I
38expect that few readers have heard of it.)
39
40Objects have individuality, and multiple names (in multiple scopes) can be bound
41to the same object. This is known as aliasing in other languages. This is
42usually not appreciated on a first glance at Python, and can be safely ignored
43when dealing with immutable basic types (numbers, strings, tuples). However,
44aliasing has an (intended!) effect on the semantics of Python code involving
45mutable objects such as lists, dictionaries, and most types representing
46entities outside the program (files, windows, etc.). This is usually used to
47the benefit of the program, since aliases behave like pointers in some respects.
48For example, passing an object is cheap since only a pointer is passed by the
49implementation; and if a function modifies an object passed as an argument, the
50caller will see the change --- this eliminates the need for two different
51argument passing mechanisms as in Pascal.
52
53
54.. _tut-scopes:
55
56Python Scopes and Name Spaces
57=============================
58
59Before introducing classes, I first have to tell you something about Python's
60scope rules. Class definitions play some neat tricks with namespaces, and you
61need to know how scopes and namespaces work to fully understand what's going on.
62Incidentally, knowledge about this subject is useful for any advanced Python
63programmer.
64
65Let's begin with some definitions.
66
67A *namespace* is a mapping from names to objects. Most namespaces are currently
68implemented as Python dictionaries, but that's normally not noticeable in any
69way (except for performance), and it may change in the future. Examples of
70namespaces are: the set of built-in names (functions such as :func:`abs`, and
71built-in exception names); the global names in a module; and the local names in
72a function invocation. In a sense the set of attributes of an object also form
73a namespace. The important thing to know about namespaces is that there is
74absolutely no relation between names in different namespaces; for instance, two
75different modules may both define a function "maximize" without confusion ---
76users of the modules must prefix it with the module name.
77
78By the way, I use the word *attribute* for any name following a dot --- for
79example, in the expression ``z.real``, ``real`` is an attribute of the object
80``z``. Strictly speaking, references to names in modules are attribute
81references: in the expression ``modname.funcname``, ``modname`` is a module
82object and ``funcname`` is an attribute of it. In this case there happens to be
83a straightforward mapping between the module's attributes and the global names
84defined in the module: they share the same namespace! [#]_
85
86Attributes may be read-only or writable. In the latter case, assignment to
87attributes is possible. Module attributes are writable: you can write
88``modname.the_answer = 42``. Writable attributes may also be deleted with the
89:keyword:`del` statement. For example, ``del modname.the_answer`` will remove
90the attribute :attr:`the_answer` from the object named by ``modname``.
91
92Name spaces are created at different moments and have different lifetimes. The
93namespace containing the built-in names is created when the Python interpreter
94starts up, and is never deleted. The global namespace for a module is created
95when the module definition is read in; normally, module namespaces also last
96until the interpreter quits. The statements executed by the top-level
97invocation of the interpreter, either read from a script file or interactively,
98are considered part of a module called :mod:`__main__`, so they have their own
99global namespace. (The built-in names actually also live in a module; this is
100called :mod:`__builtin__`.)
101
102The local namespace for a function is created when the function is called, and
103deleted when the function returns or raises an exception that is not handled
104within the function. (Actually, forgetting would be a better way to describe
105what actually happens.) Of course, recursive invocations each have their own
106local namespace.
107
108A *scope* is a textual region of a Python program where a namespace is directly
109accessible. "Directly accessible" here means that an unqualified reference to a
110name attempts to find the name in the namespace.
111
112Although scopes are determined statically, they are used dynamically. At any
113time during execution, there are at least three nested scopes whose namespaces
114are directly accessible: the innermost scope, which is searched first, contains
115the local names; the namespaces of any enclosing functions, which are searched
116starting with the nearest enclosing scope; the middle scope, searched next,
117contains the current module's global names; and the outermost scope (searched
118last) is the namespace containing built-in names.
119
120If a name is declared global, then all references and assignments go directly to
121the middle scope containing the module's global names. Otherwise, all variables
122found outside of the innermost scope are read-only (an attempt to write to such
123a variable will simply create a *new* local variable in the innermost scope,
124leaving the identically named outer variable unchanged).
125
Georg Brandl26bab5f2008-03-06 07:22:09 +0000126.. XXX mention nonlocal
127
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128Usually, the local scope references the local names of the (textually) current
129function. Outside functions, the local scope references the same namespace as
130the global scope: the module's namespace. Class definitions place yet another
131namespace in the local scope.
132
133It is important to realize that scopes are determined textually: the global
134scope of a function defined in a module is that module's namespace, no matter
135from where or by what alias the function is called. On the other hand, the
136actual search for names is done dynamically, at run time --- however, the
137language definition is evolving towards static name resolution, at "compile"
138time, so don't rely on dynamic name resolution! (In fact, local variables are
139already determined statically.)
140
Georg Brandl26bab5f2008-03-06 07:22:09 +0000141A special quirk of Python is that -- if no :keyword:`global` or
142:keyword:`nonlocal` statement is in effect -- assignments to names always go
143into the innermost scope. Assignments do not copy data --- they just bind names
144to objects. The same is true for deletions: the statement ``del x`` removes the
145binding of ``x`` from the namespace referenced by the local scope. In fact, all
146operations that introduce new names use the local scope: in particular, import
147statements and function definitions bind the module or function name in the
148local scope. (The :keyword:`global` statement can be used to indicate that
149particular variables live in the global scope.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151
152.. _tut-firstclasses:
153
154A First Look at Classes
155=======================
156
157Classes introduce a little bit of new syntax, three new object types, and some
158new semantics.
159
160
161.. _tut-classdefinition:
162
163Class Definition Syntax
164-----------------------
165
166The simplest form of class definition looks like this::
167
168 class ClassName:
169 <statement-1>
170 .
171 .
172 .
173 <statement-N>
174
175Class definitions, like function definitions (:keyword:`def` statements) must be
176executed before they have any effect. (You could conceivably place a class
177definition in a branch of an :keyword:`if` statement, or inside a function.)
178
179In practice, the statements inside a class definition will usually be function
180definitions, but other statements are allowed, and sometimes useful --- we'll
181come back to this later. The function definitions inside a class normally have
182a peculiar form of argument list, dictated by the calling conventions for
183methods --- again, this is explained later.
184
185When a class definition is entered, a new namespace is created, and used as the
186local scope --- thus, all assignments to local variables go into this new
187namespace. In particular, function definitions bind the name of the new
188function here.
189
190When a class definition is left normally (via the end), a *class object* is
191created. This is basically a wrapper around the contents of the namespace
192created by the class definition; we'll learn more about class objects in the
193next section. The original local scope (the one in effect just before the class
194definition was entered) is reinstated, and the class object is bound here to the
195class name given in the class definition header (:class:`ClassName` in the
196example).
197
198
199.. _tut-classobjects:
200
201Class Objects
202-------------
203
204Class objects support two kinds of operations: attribute references and
205instantiation.
206
207*Attribute references* use the standard syntax used for all attribute references
208in Python: ``obj.name``. Valid attribute names are all the names that were in
209the class's namespace when the class object was created. So, if the class
210definition looked like this::
211
212 class MyClass:
213 "A simple example class"
214 i = 12345
215 def f(self):
216 return 'hello world'
217
218then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning
219an integer and a function object, respectively. Class attributes can also be
220assigned to, so you can change the value of ``MyClass.i`` by assignment.
221:attr:`__doc__` is also a valid attribute, returning the docstring belonging to
222the class: ``"A simple example class"``.
223
224Class *instantiation* uses function notation. Just pretend that the class
225object is a parameterless function that returns a new instance of the class.
226For example (assuming the above class)::
227
228 x = MyClass()
229
230creates a new *instance* of the class and assigns this object to the local
231variable ``x``.
232
233The instantiation operation ("calling" a class object) creates an empty object.
234Many classes like to create objects with instances customized to a specific
235initial state. Therefore a class may define a special method named
236:meth:`__init__`, like this::
237
238 def __init__(self):
239 self.data = []
240
241When a class defines an :meth:`__init__` method, class instantiation
242automatically invokes :meth:`__init__` for the newly-created class instance. So
243in this example, a new, initialized instance can be obtained by::
244
245 x = MyClass()
246
247Of course, the :meth:`__init__` method may have arguments for greater
248flexibility. In that case, arguments given to the class instantiation operator
249are passed on to :meth:`__init__`. For example, ::
250
251 >>> class Complex:
252 ... def __init__(self, realpart, imagpart):
253 ... self.r = realpart
254 ... self.i = imagpart
255 ...
256 >>> x = Complex(3.0, -4.5)
257 >>> x.r, x.i
258 (3.0, -4.5)
259
260
261.. _tut-instanceobjects:
262
263Instance Objects
264----------------
265
266Now what can we do with instance objects? The only operations understood by
267instance objects are attribute references. There are two kinds of valid
268attribute names, data attributes and methods.
269
270*data attributes* correspond to "instance variables" in Smalltalk, and to "data
271members" in C++. Data attributes need not be declared; like local variables,
272they spring into existence when they are first assigned to. For example, if
273``x`` is the instance of :class:`MyClass` created above, the following piece of
274code will print the value ``16``, without leaving a trace::
275
276 x.counter = 1
277 while x.counter < 10:
278 x.counter = x.counter * 2
279 print x.counter
280 del x.counter
281
282The other kind of instance attribute reference is a *method*. A method is a
283function that "belongs to" an object. (In Python, the term method is not unique
284to class instances: other object types can have methods as well. For example,
285list objects have methods called append, insert, remove, sort, and so on.
286However, in the following discussion, we'll use the term method exclusively to
287mean methods of class instance objects, unless explicitly stated otherwise.)
288
289.. index:: object: method
290
291Valid method names of an instance object depend on its class. By definition,
292all attributes of a class that are function objects define corresponding
293methods of its instances. So in our example, ``x.f`` is a valid method
294reference, since ``MyClass.f`` is a function, but ``x.i`` is not, since
295``MyClass.i`` is not. But ``x.f`` is not the same thing as ``MyClass.f`` --- it
296is a *method object*, not a function object.
297
298
299.. _tut-methodobjects:
300
301Method Objects
302--------------
303
304Usually, a method is called right after it is bound::
305
306 x.f()
307
308In the :class:`MyClass` example, this will return the string ``'hello world'``.
309However, it is not necessary to call a method right away: ``x.f`` is a method
310object, and can be stored away and called at a later time. For example::
311
312 xf = x.f
313 while True:
314 print xf()
315
316will continue to print ``hello world`` until the end of time.
317
318What exactly happens when a method is called? You may have noticed that
319``x.f()`` was called without an argument above, even though the function
320definition for :meth:`f` specified an argument. What happened to the argument?
321Surely Python raises an exception when a function that requires an argument is
322called without any --- even if the argument isn't actually used...
323
324Actually, you may have guessed the answer: the special thing about methods is
325that the object is passed as the first argument of the function. In our
326example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``. In
327general, calling a method with a list of *n* arguments is equivalent to calling
328the corresponding function with an argument list that is created by inserting
329the method's object before the first argument.
330
331If you still don't understand how methods work, a look at the implementation can
332perhaps clarify matters. When an instance attribute is referenced that isn't a
333data attribute, its class is searched. If the name denotes a valid class
334attribute that is a function object, a method object is created by packing
335(pointers to) the instance object and the function object just found together in
336an abstract object: this is the method object. When the method object is called
337with an argument list, it is unpacked again, a new argument list is constructed
338from the instance object and the original argument list, and the function object
339is called with this new argument list.
340
341
342.. _tut-remarks:
343
344Random Remarks
345==============
346
Georg Brandlb19be572007-12-29 10:57:00 +0000347.. These should perhaps be placed more carefully...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000348
349Data attributes override method attributes with the same name; to avoid
350accidental name conflicts, which may cause hard-to-find bugs in large programs,
351it is wise to use some kind of convention that minimizes the chance of
352conflicts. Possible conventions include capitalizing method names, prefixing
353data attribute names with a small unique string (perhaps just an underscore), or
354using verbs for methods and nouns for data attributes.
355
356Data attributes may be referenced by methods as well as by ordinary users
357("clients") of an object. In other words, classes are not usable to implement
358pure abstract data types. In fact, nothing in Python makes it possible to
359enforce data hiding --- it is all based upon convention. (On the other hand,
360the Python implementation, written in C, can completely hide implementation
361details and control access to an object if necessary; this can be used by
362extensions to Python written in C.)
363
364Clients should use data attributes with care --- clients may mess up invariants
365maintained by the methods by stamping on their data attributes. Note that
366clients may add data attributes of their own to an instance object without
367affecting the validity of the methods, as long as name conflicts are avoided ---
368again, a naming convention can save a lot of headaches here.
369
370There is no shorthand for referencing data attributes (or other methods!) from
371within methods. I find that this actually increases the readability of methods:
372there is no chance of confusing local variables and instance variables when
373glancing through a method.
374
375Often, the first argument of a method is called ``self``. This is nothing more
376than a convention: the name ``self`` has absolutely no special meaning to
377Python. (Note, however, that by not following the convention your code may be
378less readable to other Python programmers, and it is also conceivable that a
379*class browser* program might be written that relies upon such a convention.)
380
381Any function object that is a class attribute defines a method for instances of
382that class. It is not necessary that the function definition is textually
383enclosed in the class definition: assigning a function object to a local
384variable in the class is also ok. For example::
385
386 # Function defined outside the class
387 def f1(self, x, y):
388 return min(x, x+y)
389
390 class C:
391 f = f1
392 def g(self):
393 return 'hello world'
394 h = g
395
396Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to
397function objects, and consequently they are all methods of instances of
398:class:`C` --- ``h`` being exactly equivalent to ``g``. Note that this practice
399usually only serves to confuse the reader of a program.
400
401Methods may call other methods by using method attributes of the ``self``
402argument::
403
404 class Bag:
405 def __init__(self):
406 self.data = []
407 def add(self, x):
408 self.data.append(x)
409 def addtwice(self, x):
410 self.add(x)
411 self.add(x)
412
413Methods may reference global names in the same way as ordinary functions. The
414global scope associated with a method is the module containing the class
415definition. (The class itself is never used as a global scope!) While one
416rarely encounters a good reason for using global data in a method, there are
417many legitimate uses of the global scope: for one thing, functions and modules
418imported into the global scope can be used by methods, as well as functions and
419classes defined in it. Usually, the class containing the method is itself
420defined in this global scope, and in the next section we'll find some good
421reasons why a method would want to reference its own class!
422
423
424.. _tut-inheritance:
425
426Inheritance
427===========
428
429Of course, a language feature would not be worthy of the name "class" without
430supporting inheritance. The syntax for a derived class definition looks like
431this::
432
433 class DerivedClassName(BaseClassName):
434 <statement-1>
435 .
436 .
437 .
438 <statement-N>
439
440The name :class:`BaseClassName` must be defined in a scope containing the
441derived class definition. In place of a base class name, other arbitrary
442expressions are also allowed. This can be useful, for example, when the base
443class is defined in another module::
444
445 class DerivedClassName(modname.BaseClassName):
446
447Execution of a derived class definition proceeds the same as for a base class.
448When the class object is constructed, the base class is remembered. This is
449used for resolving attribute references: if a requested attribute is not found
450in the class, the search proceeds to look in the base class. This rule is
451applied recursively if the base class itself is derived from some other class.
452
453There's nothing special about instantiation of derived classes:
454``DerivedClassName()`` creates a new instance of the class. Method references
455are resolved as follows: the corresponding class attribute is searched,
456descending down the chain of base classes if necessary, and the method reference
457is valid if this yields a function object.
458
459Derived classes may override methods of their base classes. Because methods
460have no special privileges when calling other methods of the same object, a
461method of a base class that calls another method defined in the same base class
462may end up calling a method of a derived class that overrides it. (For C++
Georg Brandlb19be572007-12-29 10:57:00 +0000463programmers: all methods in Python are effectively ``virtual``.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000464
465An overriding method in a derived class may in fact want to extend rather than
466simply replace the base class method of the same name. There is a simple way to
467call the base class method directly: just call ``BaseClassName.methodname(self,
468arguments)``. This is occasionally useful to clients as well. (Note that this
469only works if the base class is defined or imported directly in the global
470scope.)
471
472
473.. _tut-multiple:
474
475Multiple Inheritance
476--------------------
477
478Python supports a limited form of multiple inheritance as well. A class
479definition with multiple base classes looks like this::
480
481 class DerivedClassName(Base1, Base2, Base3):
482 <statement-1>
483 .
484 .
485 .
486 <statement-N>
487
488For old-style classes, the only rule is depth-first, left-to-right. Thus, if an
489attribute is not found in :class:`DerivedClassName`, it is searched in
490:class:`Base1`, then (recursively) in the base classes of :class:`Base1`, and
491only if it is not found there, it is searched in :class:`Base2`, and so on.
492
493(To some people breadth first --- searching :class:`Base2` and :class:`Base3`
494before the base classes of :class:`Base1` --- looks more natural. However, this
495would require you to know whether a particular attribute of :class:`Base1` is
496actually defined in :class:`Base1` or in one of its base classes before you can
497figure out the consequences of a name conflict with an attribute of
498:class:`Base2`. The depth-first rule makes no differences between direct and
499inherited attributes of :class:`Base1`.)
500
Georg Brandla7395032007-10-21 12:15:05 +0000501For :term:`new-style class`\es, the method resolution order changes dynamically
502to support cooperative calls to :func:`super`. This approach is known in some
Georg Brandl8ec7f652007-08-15 14:28:01 +0000503other multiple-inheritance languages as call-next-method and is more powerful
504than the super call found in single-inheritance languages.
505
506With new-style classes, dynamic ordering is necessary because all cases of
507multiple inheritance exhibit one or more diamond relationships (where one at
508least one of the parent classes can be accessed through multiple paths from the
509bottommost class). For example, all new-style classes inherit from
510:class:`object`, so any case of multiple inheritance provides more than one path
511to reach :class:`object`. To keep the base classes from being accessed more
512than once, the dynamic algorithm linearizes the search order in a way that
513preserves the left-to-right ordering specified in each class, that calls each
514parent only once, and that is monotonic (meaning that a class can be subclassed
515without affecting the precedence order of its parents). Taken together, these
516properties make it possible to design reliable and extensible classes with
517multiple inheritance. For more detail, see
518http://www.python.org/download/releases/2.3/mro/.
519
520
521.. _tut-private:
522
523Private Variables
524=================
525
526There is limited support for class-private identifiers. Any identifier of the
527form ``__spam`` (at least two leading underscores, at most one trailing
528underscore) is textually replaced with ``_classname__spam``, where ``classname``
529is the current class name with leading underscore(s) stripped. This mangling is
530done without regard to the syntactic position of the identifier, so it can be
531used to define class-private instance and class variables, methods, variables
532stored in globals, and even variables stored in instances. private to this class
533on instances of *other* classes. Truncation may occur when the mangled name
534would be longer than 255 characters. Outside classes, or when the class name
535consists of only underscores, no mangling occurs.
536
537Name mangling is intended to give classes an easy way to define "private"
538instance variables and methods, without having to worry about instance variables
539defined by derived classes, or mucking with instance variables by code outside
540the class. Note that the mangling rules are designed mostly to avoid accidents;
541it still is possible for a determined soul to access or modify a variable that
542is considered private. This can even be useful in special circumstances, such
543as in the debugger, and that's one reason why this loophole is not closed.
544(Buglet: derivation of a class with the same name as the base class makes use of
545private variables of the base class possible.)
546
547Notice that code passed to ``exec``, ``eval()`` or ``execfile()`` does not
548consider the classname of the invoking class to be the current class; this is
549similar to the effect of the ``global`` statement, the effect of which is
550likewise restricted to code that is byte-compiled together. The same
551restriction applies to ``getattr()``, ``setattr()`` and ``delattr()``, as well
552as when referencing ``__dict__`` directly.
553
554
555.. _tut-odds:
556
557Odds and Ends
558=============
559
560Sometimes it is useful to have a data type similar to the Pascal "record" or C
561"struct", bundling together a few named data items. An empty class definition
562will do nicely::
563
564 class Employee:
565 pass
566
567 john = Employee() # Create an empty employee record
568
569 # Fill the fields of the record
570 john.name = 'John Doe'
571 john.dept = 'computer lab'
572 john.salary = 1000
573
574A piece of Python code that expects a particular abstract data type can often be
575passed a class that emulates the methods of that data type instead. For
576instance, if you have a function that formats some data from a file object, you
577can define a class with methods :meth:`read` and :meth:`readline` that get the
578data from a string buffer instead, and pass it as an argument.
579
Georg Brandlb19be572007-12-29 10:57:00 +0000580.. (Unfortunately, this technique has its limitations: a class can't define
581 operations that are accessed by special syntax such as sequence subscripting
582 or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will
583 not cause the interpreter to read further input from it.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000584
585Instance method objects have attributes, too: ``m.im_self`` is the instance
586object with the method :meth:`m`, and ``m.im_func`` is the function object
587corresponding to the method.
588
589
590.. _tut-exceptionclasses:
591
592Exceptions Are Classes Too
593==========================
594
595User-defined exceptions are identified by classes as well. Using this mechanism
596it is possible to create extensible hierarchies of exceptions.
597
598There are two new valid (semantic) forms for the raise statement::
599
600 raise Class, instance
601
602 raise instance
603
604In the first form, ``instance`` must be an instance of :class:`Class` or of a
605class derived from it. The second form is a shorthand for::
606
607 raise instance.__class__, instance
608
609A class in an except clause is compatible with an exception if it is the same
610class or a base class thereof (but not the other way around --- an except clause
611listing a derived class is not compatible with a base class). For example, the
612following code will print B, C, D in that order::
613
614 class B:
615 pass
616 class C(B):
617 pass
618 class D(C):
619 pass
620
621 for c in [B, C, D]:
622 try:
623 raise c()
624 except D:
625 print "D"
626 except C:
627 print "C"
628 except B:
629 print "B"
630
631Note that if the except clauses were reversed (with ``except B`` first), it
632would have printed B, B, B --- the first matching except clause is triggered.
633
634When an error message is printed for an unhandled exception, the exception's
635class name is printed, then a colon and a space, and finally the instance
636converted to a string using the built-in function :func:`str`.
637
638
639.. _tut-iterators:
640
641Iterators
642=========
643
644By now you have probably noticed that most container objects can be looped over
645using a :keyword:`for` statement::
646
647 for element in [1, 2, 3]:
648 print element
649 for element in (1, 2, 3):
650 print element
651 for key in {'one':1, 'two':2}:
652 print key
653 for char in "123":
654 print char
655 for line in open("myfile.txt"):
656 print line
657
658This style of access is clear, concise, and convenient. The use of iterators
659pervades and unifies Python. Behind the scenes, the :keyword:`for` statement
660calls :func:`iter` on the container object. The function returns an iterator
661object that defines the method :meth:`next` which accesses elements in the
662container one at a time. When there are no more elements, :meth:`next` raises a
663:exc:`StopIteration` exception which tells the :keyword:`for` loop to terminate.
664This example shows how it all works::
665
666 >>> s = 'abc'
667 >>> it = iter(s)
668 >>> it
669 <iterator object at 0x00A1DB50>
670 >>> it.next()
671 'a'
672 >>> it.next()
673 'b'
674 >>> it.next()
675 'c'
676 >>> it.next()
677
678 Traceback (most recent call last):
679 File "<stdin>", line 1, in ?
680 it.next()
681 StopIteration
682
683Having seen the mechanics behind the iterator protocol, it is easy to add
684iterator behavior to your classes. Define a :meth:`__iter__` method which
685returns an object with a :meth:`next` method. If the class defines
686:meth:`next`, then :meth:`__iter__` can just return ``self``::
687
688 class Reverse:
689 "Iterator for looping over a sequence backwards"
690 def __init__(self, data):
691 self.data = data
692 self.index = len(data)
693 def __iter__(self):
694 return self
695 def next(self):
696 if self.index == 0:
697 raise StopIteration
698 self.index = self.index - 1
699 return self.data[self.index]
700
701 >>> for char in Reverse('spam'):
702 ... print char
703 ...
704 m
705 a
706 p
707 s
708
709
710.. _tut-generators:
711
712Generators
713==========
714
Georg Brandlcf3fb252007-10-21 10:52:38 +0000715:term:`Generator`\s are a simple and powerful tool for creating iterators. They
716are written like regular functions but use the :keyword:`yield` statement
717whenever they want to return data. Each time :meth:`next` is called, the
718generator resumes where it left-off (it remembers all the data values and which
719statement was last executed). An example shows that generators can be trivially
720easy to create::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721
722 def reverse(data):
723 for index in range(len(data)-1, -1, -1):
724 yield data[index]
725
726 >>> for char in reverse('golf'):
727 ... print char
728 ...
729 f
730 l
731 o
732 g
733
734Anything that can be done with generators can also be done with class based
735iterators as described in the previous section. What makes generators so
736compact is that the :meth:`__iter__` and :meth:`next` methods are created
737automatically.
738
739Another key feature is that the local variables and execution state are
740automatically saved between calls. This made the function easier to write and
741much more clear than an approach using instance variables like ``self.index``
742and ``self.data``.
743
744In addition to automatic method creation and saving program state, when
745generators terminate, they automatically raise :exc:`StopIteration`. In
746combination, these features make it easy to create iterators with no more effort
747than writing a regular function.
748
749
750.. _tut-genexps:
751
752Generator Expressions
753=====================
754
755Some simple generators can be coded succinctly as expressions using a syntax
756similar to list comprehensions but with parentheses instead of brackets. These
757expressions are designed for situations where the generator is used right away
758by an enclosing function. Generator expressions are more compact but less
759versatile than full generator definitions and tend to be more memory friendly
760than equivalent list comprehensions.
761
762Examples::
763
764 >>> sum(i*i for i in range(10)) # sum of squares
765 285
766
767 >>> xvec = [10, 20, 30]
768 >>> yvec = [7, 5, 3]
769 >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
770 260
771
772 >>> from math import pi, sin
773 >>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91))
774
775 >>> unique_words = set(word for line in page for word in line.split())
776
777 >>> valedictorian = max((student.gpa, student.name) for student in graduates)
778
779 >>> data = 'golf'
780 >>> list(data[i] for i in range(len(data)-1,-1,-1))
781 ['f', 'l', 'o', 'g']
782
783
784
785.. rubric:: Footnotes
786
787.. [#] Except for one thing. Module objects have a secret read-only attribute called
788 :attr:`__dict__` which returns the dictionary used to implement the module's
789 namespace; the name :attr:`__dict__` is an attribute but not a global name.
790 Obviously, using this violates the abstraction of namespace implementation, and
791 should be restricted to things like post-mortem debuggers.
792