12.5.3 The Writer Interface

formatter-impls.html | module-formatter.html | writer-impls.html | Python Library Reference | contents.html | genindex.html
---
## 12.5.3 The Writer Interface
Interfaces to create writers are dependent on the specific writer
class being instantiated. The interfaces described below are the
required interfaces which all writers must support once initialized.
Note that while most applications can use the
AbstractFormatter class as a formatter, the writer must
typically be provided by the application.


12.13.3 Exceptions

xdr-unpacker-objects.html | module-xdrlib.html | module-mailcap.html | Python Library Reference | contents.html | genindex.html
---
## 12.13.3 Exceptions
Exceptions in this module are coded as class instances:
Here is an example of how you would catch one of these exceptions:


12.13.1 Packer Objects

module-xdrlib.html | module-xdrlib.html | xdr-unpacker-objects.html | Python Library Reference | contents.html | genindex.html
---
## 12.13.1 Packer Objects
Packer instances have the following methods:
In general, you can pack any of the most common XDR data types by
calling the appropriate `pack_ type ()` method. Each method
takes a single argument, the value to pack. The following simple data
type packing methods are supported: pack_uint(),
pack_int(), pack_enum(), pack_bool(),
pack_uhyper(), and pack_hyper().
The following methods support packing strings, bytes, and opaque data:
The following methods support packing arrays and lists:


12.13.2 Unpacker Objects

xdr-packer-objects.html | module-xdrlib.html | xdr-exceptions.html | Python Library Reference | contents.html | genindex.html
---
## 12.13.2 Unpacker Objects
The Unpacker class offers the following methods:
In addition, every data type that can be packed with a Packer,
can be unpacked with an Unpacker. Unpacking methods are of the
form `unpack_ type ()`, and take no arguments. They return the
unpacked object.
In addition, the following methods unpack strings, bytes, and opaque
data:
The following methods support unpacking arrays and lists:


12.4.1 XML Namespaces

module-xmllib.html | module-xmllib.html | module-formatter.html | Python Library Reference | contents.html | genindex.html
---
## 12.4.1 XML Namespaces
This module has support for XML namespaces as defined in the XML
Namespaces proposed recommendation.
Tag and attribute names that are defined in an XML namespace are
handled as if the name of the tag or element consisted of the
namespace (i.e. the URL that defines the namespace) followed by a
space and the name of the tag or attribute. For instance, the tag
`<html xmlns='http://www.w3.org/TR/REC-html40'>` is treated as if
the tag name was `'http://www.w3.org/TR/REC-html40 html'`, and
the tag `<html:a href='http://frob.com'>` inside the above
mentioned element is treated as if the tag name were
`'http://www.w3.org/TR/REC-html40 a'` and the attribute name as
if it were `'http://www.w3.org/TR/REC-html40 src'`.


7.14.1 ZipFile Objects

node175.html | node175.html | module-rlcompleter.html | Python Library Reference | contents.html | genindex.html
---
## 7.14.1 ZipFile Objects
XXX explain the "extra" string for the ZIP format
The class ZipFile has these methods:


About this document ...

genindex.html | mac.html | Macintosh Library Modules | contents.html | genindex.html
---
# About this document ...
Macintosh Library Modules,
September 18, 2000, Release 1.6
This document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.
LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©
1993, 1994, 1995, 1996, 1997, Nikos
Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of
Leeds, and Copyright © 1997, 1998, Ross
Moore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,
Sydney.
The application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python
documentation has been heavily tailored by Fred L. Drake,
Jr. Original navigation icons were contributed by Christopher
Petrilli.
---
## Comments and Questions
General comments and questions regarding this document should
be sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in
this document, please report the bug at the Python Bug
Tracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).
Questions regarding how to use the information in this
document should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and
carries the same content).
For any of these channels, please be sure not to send HTML email.
Thanks.
---
genindex.html | mac.html | Macintosh Library Modules | contents.html | genindex.html
---


16.1 AEServer Objects

module-MiniAEFrame.html | module-MiniAEFrame.html | modindex.html | Macintosh Library Modules | contents.html | genindex.html
---
## 16.1 AEServer Objects
Note that there are some serious problems with the current
design. AppleEvents which have non-identifier 4-character designators
for arguments are not implementable, and it is not possible to return
an error to the originator. This will be addressed in a future
release.


7.2 Alias Objects

fsspec-objects.html | module-macfs.html | finfo-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
## 7.2 Alias Objects
Note that it is currently not possible to directly manipulate a
resource as an Alias object. Hence, after calling
Update() or after Resolve() indicates that the alias
has changed the Python program is responsible for getting the
data value from the Alias object and modifying the
resource.


15.1 Application Objects

module-FrameWork.html | module-FrameWork.html | window-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
## 15.1 Application Objects
Application objects have the following methods, among others:


4.1 Connection Objects

module-ctb.html | module-ctb.html | module-macconsole.html | Macintosh Library Modules | contents.html | genindex.html
---
## 4.1 Connection Objects
For all connection methods that take a timeout argument, a value
of `-1` is indefinite, meaning that the command runs to completion.


Contents

front.html | mac.html | intro.html | Macintosh Library Modules | genindex.html
---
## Contents


15.3 ControlsWindow Object

window-objects.html | module-FrameWork.html | scrolledwindow-object.html | Macintosh Library Modules | contents.html | genindex.html
---
## 15.3 ControlsWindow Object
ControlsWindow objects have the following methods besides those of
`Window` objects:


15.5 DialogWindow Objects

scrolledwindow-object.html | module-FrameWork.html | module-MiniAEFrame.html | Macintosh Library Modules | contents.html | genindex.html
---
## 15.5 DialogWindow Objects
DialogWindow objects have the following methods besides those of
`Window` objects:


6.1 DNR Result Objects

module-macdnr.html | module-macdnr.html | module-macfs.html | Macintosh Library Modules | contents.html | genindex.html
---
## 6.1 DNR Result Objects
Since the DNR calls all execute asynchronously you do not get the
results back immediately. Instead, you get a dnr result object. You
can check this object to see whether the query is complete, and access
its attributes to obtain the information when it is.
Alternatively, you can also reference the result attributes directly,
this will result in an implicit wait for the query to complete.
The rtnCode and cname attributes are always
available, the others depend on the type of query (address, hinfo or
mx).
The simplest way to use the module to convert names to dotted-decimal
strings, without worrying about idle time, etc:


7.3 FInfo Objects

alias-objects.html | module-macfs.html | module-ic.html | Macintosh Library Modules | contents.html | genindex.html
---
## 7.3 FInfo Objects
See Inside Macintosh: Files for a complete description of what
the various fields mean.


Front Matter

mac.html | mac.html | contents.html | Macintosh Library Modules | contents.html | genindex.html
---
# Front Matter
BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization (``Licensee'') accessing and otherwise
using this software in source or binary form and its associated
documentation (``the Software'').
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an ``AS IS''
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the ``BeOpen Python'' logos available
at http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI OPEN SOURCE LICENSE AGREEMENT
Python 1.6 is made available subject to the terms and conditions in
CNRI's License Agreement. This Agreement together with Python 1.6 may
be located on the Internet using the following unique, persistent
identifier (known as a handle): 1895.22/1012. This Agreement may also
be obtained from a proxy server on the Internet using the following
URL: http://hdl.handle.net/1895.22/1012.
CWI PERMISSIONS STATEMENT AND DISCLAIMER
Copyright © 1991 - 1995, Stichting Mathematisch Centrum
Amsterdam, The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
### Abstract:
This library reference manual documents Python's extensions for the
Macintosh. It should be used in conjunction with the
Python Library Reference (../lib/lib.html), which documents
the standard library and built-in types.
This manual assumes basic knowledge about the Python language. For an
informal introduction to Python, see the
Python Tutorial (../tut/tut.html); the
Python Reference Manual (../ref/ref.html) remains the
highest authority on syntactic and semantic questions. Finally, the
manual entitled Extending and Embedding
the Python Interpreter (../ext/ext.html) describes how to add new extensions to Python
and how to embed it in other applications.


7.1 FSSpec objects

module-macfs.html | module-macfs.html | alias-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
## 7.1 FSSpec objects


Index

modindex.html | mac.html | about.html | Macintosh Library Modules | contents.html
---
## Index
---
_ (#letter-_) |
a (#letter-a) |
b (#letter-b) |
c (#letter-c) |
d (#letter-d) |
e (#letter-e) |
f (#letter-f) |
g (#letter-g) |
h (#letter-h) |
i (#letter-i) |
l (#letter-l) |
m (#letter-m) |
n (#letter-n) |
o (#letter-o) |
p (#letter-p) |
r (#letter-r) |
s (#letter-s) |
t (#letter-t) |
u (#letter-u) |
v (#letter-v) |
w (#letter-w) |
x (#letter-x)
---
## _ (underscore)
---
## A
---
## B
---
## C
---
## D
---
## E
---
## F
---
## G
---
## H
---
## I
---
## L
---
## M
---
## N
---
## O
---
## P
---
## R
---
## S
---
## T
---
## U
---
## V
---
## W
---
## X


Macintosh Library Modules

../index.html | front.html | Macintosh Library Modules | contents.html | genindex.html
---
# Macintosh Library Modules
Guido van Rossum
Fred L. Drake, Jr., editor
BeOpen PythonLabs
E-mail: python-docs@python.org
September 18, 2000
Release 1.6


1 Introduction

contents.html | contents.html | module-mac.html | Macintosh Library Modules | contents.html | genindex.html
---
# 1 Introduction
The modules in this manual are available on the Apple Macintosh only.
Aside from the modules described here there are also interfaces to
various MacOS toolboxes, which are currently not extensively
described. The toolboxes for which modules exist are:
AE (Apple Events),
Cm (Component Manager),
Ctl (Control Manager),
Dlg (Dialog Manager),
Evt (Event Manager),
Fm (Font Manager),
List (List Manager),
Menu (Moenu Manager),
Qd (QuickDraw),
Qt (QuickTime),
Res (Resource Manager and Handles),
Scrap (Scrap Manager),
Snd (Sound Manager),
TE (TextEdit),
Waste (non-Apple TextEdit replacement) and
Win (Window Manager).
If applicable the module will define a number of Python objects for
the various structures declared by the toolbox, and operations will be
implemented as methods of the object. Other operations will be
implemented as functions in the module. Not all operations possible in
C will also be possible in Python (callbacks are often a problem), and
parameters will occasionally be different in Python (input and output
buffers, especially). All methods and functions have a `__doc__`string describing their arguments and return values, and for
additional description you are referred to Inside
Macintosh or similar works.
The following modules are documented here:
mac (module-mac.html) | Implementations for the os module.
macpath (module-macpath.html) | MacOS path manipulation functions.
ctb (module-ctb.html) | Interfaces to the Communications Tool Box. Only the Connection
Manager is supported.
macconsole (module-macconsole.html) | Think C's console package.
macdnr (module-macdnr.html) | Interfaces to the Macintosh Domain Name Resolver.
macfs (module-macfs.html) | Support for FSSpec, the Alias Manager,
finder aliases, and the Standard File package.
ic (module-ic.html) | Access to Internet Config.
MacOS (module-MacOS.html) | Access to MacOS specific interpreter features.
macostools (module-macostools.html) | Convenience routines for file manipulation.
findertools (module-findertools.html) | Wrappers around the finder's Apple Events interface.
mactcp (module-mactcp.html) | The MacTCP interfaces.
macspeech (module-macspeech.html) | Interface to the Macintosh Speech Manager.
EasyDialogs (module-EasyDialogs.html) | Basic Macintosh dialogs.
FrameWork (module-FrameWork.html) | Interactive application framework.
MiniAEFrame (module-MiniAEFrame.html) | Support to act as an Open Scripting Architecture (OSA) server
(``Apple Events'').


Macintosh Library Modules


Module Index

aeserver-objects.html | mac.html | genindex.html | Macintosh Library Modules | contents.html | genindex.html
---
## Module Index
Some module names are followed by an annotation indicating what
platform they are available on.


module-macpath.html | contents.html | connection-object.html | Macintosh Library Modules | contents.html | genindex.html
---
# 4 ctb --
Interface to the Communications Tool Box
Availability: Macintosh.
This module provides a partial interface to the Macintosh
Communications Toolbox. Currently, only Connection Manager tools are
supported. It may not be available in all Mac Python versions.


speech-channel-objects.html | contents.html | module-FrameWork.html | Macintosh Library Modules | contents.html | genindex.html
---
# 14 EasyDialogs --
Basic Macintosh dialogs
Availability: Macintosh.
The EasyDialogs module contains some simple dialogs for
the Macintosh, modelled after the
stdwin dialogs with similar names. All
routines have an optional parameter id with which you can
override the DLOG resource used for the dialog, as long as the item
numbers correspond. See the source for details.
The EasyDialogs module defines the following functions:


module-macostools.html | contents.html | module-mactcp.html | Macintosh Library Modules | contents.html | genindex.html
---
# 11 findertools --
The finder's Apple Events interface
Availability: Macintosh.
This module contains routines that give Python programs access to some
functionality provided by the finder. They are implemented as wrappers
around the AppleEvent interface to the finder.
All file and folder parameters can be specified either as full
pathnames or as FSSpec objects.
The findertools module defines the following functions:


module-EasyDialogs.html | contents.html | application-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
# 15 FrameWork --
Interactive application framework
Availability: Macintosh.
The FrameWork module contains classes that together provide a
framework for an interactive Macintosh application. The programmer
builds an application by creating subclasses that override various
methods of the bases classes, thereby implementing the functionality
wanted. Overriding functionality can often be done on various
different levels, i.e. to handle clicks in a single dialog window in a
non-standard way it is not necessary to override the complete event
handling.
The FrameWork is still very much work-in-progress, and the
documentation describes only the most important functionality, and not
in the most logical manner at that. Examine the source or the examples
for more details.
The FrameWork module defines the following functions:


8 ic -- Access to Internet Config

finfo-objects.html | contents.html | node18.html | Macintosh Library Modules | contents.html | genindex.html
---
# 8 ic --
Access to Internet Config
Availability: Macintosh.
This module provides access to Macintosh Internet
Config package,
which stores preferences for Internet programs such as mail address,
default homepage, etc. Also, Internet Config contains an elaborate set
of mappings from Macintosh creator/type codes to foreign filename
extensions plus information on how to transfer files (binary, ascii,
etc).
There is a low-level companion module
icglue which provides the basic
Internet Config access functionality. This low-level module is not
documented, but the docstrings of the routines document the parameters
and the routine names are the same as for the Pascal or C API to
Internet Config, so the standard IC programmers' documentation can be
used if this module is needed.
The ic module defines the error exception and
symbolic names for all error codes Internet Config can produce; see
the source for details.
The ic module defines the following class and function:


intro.html | contents.html | module-macpath.html | Macintosh Library Modules | contents.html | genindex.html
---
# 2 mac --
Implementations for the os module
Availability: Macintosh.
This module implements the operating system dependent functionality
provided by the standard module os. It is
best accessed through the os module.
The following functions are available in this module:
chdir(),
close(),
dup(),
fdopen(),
getcwd(),
lseek(),
listdir(),
mkdir(),
open(),
read(),
rename(),
rmdir(),
stat(),
sync(),
unlink(),
write(),
as well as the exception error. Note that the times
returned by stat() are floating-point values, like all time
values in MacPython.
One additional function is available:


connection-object.html | contents.html | node9.html | Macintosh Library Modules | contents.html | genindex.html
---
# 5 macconsole --
Think C's console package
Availability: Macintosh.
This module is available on the Macintosh, provided Python has been
built using the Think C compiler. It provides an interface to the
Think console package, with which basic text windows can be created.


node10.html | contents.html | dnr-result-object.html | Macintosh Library Modules | contents.html | genindex.html
---
# 6 macdnr --
Interface to the Macintosh Domain Name Resolver
Availability: Macintosh.
This module provides an interface to the Macintosh Domain Name
Resolver. It is usually used in conjunction with the mactcp (module-mactcp.html)
module, to map hostnames to IP addresses. It may not be available in
all Mac Python versions.
The macdnr module defines the following functions:


7 macfs -- Various file system services

dnr-result-object.html | contents.html | fsspec-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
# 7 macfs --
Various file system services
Availability: Macintosh.
This module provides access to Macintosh FSSpec handling, the Alias
Manager, finder aliases and the Standard File package.
Whenever a function or method expects a file argument, this
argument can be one of three things: (1) a full or partial Macintosh
pathname, (2) an FSSpec object or (3) a 3-tuple `( wdRefNum , parID , name )` as described in Inside
Macintosh: Files. A description of aliases and the Standard File
package can also be found there.


node18.html | contents.html | module-macostools.html | Macintosh Library Modules | contents.html | genindex.html
---
# 9 MacOS --
Access to MacOS interpreter features
Availability: Macintosh.
This module provides access to MacOS specific functionality in the
Python interpreter, such as how the interpreter eventloop functions
and the like. Use with care.
Note the capitalisation of the module name, this is a historical
artifact.


module-MacOS.html | contents.html | module-findertools.html | Macintosh Library Modules | contents.html | genindex.html
---
# 10 macostools --
Convenience routines for file manipulation
Availability: Macintosh.
This module contains some convenience routines for file-manipulation
on the Macintosh.
The macostools module defines the following functions:
Note that the process of creating finder aliases is not specified in
the Apple documentation. Hence, aliases created with mkalias()
could conceivably have incompatible behaviour in some cases.


module-mac.html | contents.html | module-ctb.html | Macintosh Library Modules | contents.html | genindex.html
---
# 3 macpath --
MacOS path manipulation functions
This module is the Macintosh implementation of the os.path
module. It is most portably accessed as
os.path. Refer to the
Python Library Reference (../lib/lib.html) for
documentation of os.path.


node25.html | contents.html | voice-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
# 13 macspeech --
Interface to the Macintosh Speech Manager
Availability: Macintosh.
This module provides an interface to the Macintosh Speech Manager,
allowing you to let the Macintosh utter phrases. You need a version of
the Speech Manager extension (version 1 and 2 have been tested) in
your Extensions folder for this to work. The module does not
provide full access to all features of the Speech Manager yet. It may
not be available in all Mac Python versions.


12 mactcp -- The MacTCP interfaces

module-findertools.html | contents.html | node23.html | Macintosh Library Modules | contents.html | genindex.html
---
# 12 mactcp --
The MacTCP interfaces
Availability: Macintosh.
This module provides an interface to the Macintosh TCP/IP driver MacTCP. There is an accompanying module,
macdnr (module-macdnr.html), which provides an interface
to the name-server (allowing you to translate hostnames to IP
addresses), a module MACTCPconst
which has symbolic names for constants constants used by MacTCP. Since
the built-in module socket is also
available on the Macintosh it is usually easier to use sockets instead
of the Macintosh-specific MacTCP API.
A complete description of the MacTCP interface can be found in the
Apple MacTCP API documentation.


dialogwindow-objects.html | contents.html | aeserver-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
# 16 MiniAEFrame --
Open Scripting Architecture server support
Availability: Macintosh.
The module MiniAEFrame provides a framework for an application
that can function as an Open Scripting Architecture
(OSA) server, i.e. receive and process
AppleEvents. It can be used in conjunction with
FrameWork (module-FrameWork.html) or standalone.
This module is temporary, it will eventually be replaced by a module
that handles argument names better and possibly automates making your
application scriptable.
The MiniAEFrame module defines the following classes:


5.2 console window object

node9.html | module-macconsole.html | module-macdnr.html | Macintosh Library Modules | contents.html | genindex.html
---
## 5.2 console window object


8.1 IC Objects

module-ic.html | module-ic.html | module-MacOS.html | Macintosh Library Modules | contents.html | genindex.html
---
## 8.1 IC Objects
IC objects have a mapping interface, hence to obtain the mail
address you simply get `ic ['MailAddress']`. Assignment also
works, and changes the option in the configuration file.
The module knows about various datatypes, and converts the internal IC
representation to a ``logical'' Python data structure. Running the
ic module standalone will run a test program that lists all
keys and values in your IC database, this will have to server as
documentation.
If the module does not know how to represent the data it returns an
instance of the `ICOpaqueData` type, with the raw data in its
data attribute. Objects of this type are also acceptable values
for assignment.
Besides the dictionary interface, IC objects have the
following methods:


12.1 TCP Stream Objects

module-mactcp.html | module-mactcp.html | node24.html | Macintosh Library Modules | contents.html | genindex.html
---
## 12.1 TCP Stream Objects


12.2 TCP Status Objects

node23.html | module-mactcp.html | node25.html | Macintosh Library Modules | contents.html | genindex.html
---
## 12.2 TCP Status Objects
This object has no methods, only some members holding information on
the connection. A complete description of all fields in this objects
can be found in the Apple documentation. The most interesting ones are:


12.3 UDP Stream Objects

node24.html | module-mactcp.html | module-macspeech.html | Macintosh Library Modules | contents.html | genindex.html
---
## 12.3 UDP Stream Objects
Note that, unlike the name suggests, there is nothing stream-like
about UDP.


5.1 macconsole options object

module-macconsole.html | module-macconsole.html | node10.html | Macintosh Library Modules | contents.html | genindex.html
---
## 5.1 macconsole options object
These options are examined when a window is created:


15.4 ScrolledWindow Object

controlswindow-object.html | module-FrameWork.html | dialogwindow-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
## 15.4 ScrolledWindow Object
ScrolledWindow objects are ControlsWindow objects with the following
extra methods:


13.2 Speech Channel Objects

voice-objects.html | module-macspeech.html | module-EasyDialogs.html | Macintosh Library Modules | contents.html | genindex.html
---
## 13.2 Speech Channel Objects
A Speech Channel object allows you to speak strings with slightly more
control than SpeakString(), and allows you to use multiple
speakers at the same time. Please note that channel pitch and rate are
interrelated in some way, so that to make your Macintosh sing you will
have to adjust both.


13.1 Voice Objects

module-macspeech.html | module-macspeech.html | speech-channel-objects.html | Macintosh Library Modules | contents.html | genindex.html
---
## 13.1 Voice Objects
Voice objects contain the description of a voice. It is currently not
yet possible to access the parameters of a voice.


15.2 Window Objects

application-objects.html | module-FrameWork.html | controlswindow-object.html | Macintosh Library Modules | contents.html | genindex.html
---
## 15.2 Window Objects
Window objects have the following methods, among others:


Global Module Index

./ | Global Module Index
---
## Global Module Index
Some module names are followed by an annotation indicating what
platform they are available on.


About this document ...

genindex.html | ref.html | Python Reference Manual | contents.html | genindex.html
---
# About this document ...
Python Reference Manual,
September 18, 2000, Release 1.6
This document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.
LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©
1993, 1994, 1995, 1996, 1997, Nikos
Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of
Leeds, and Copyright © 1997, 1998, Ross
Moore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,
Sydney.
The application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python
documentation has been heavily tailored by Fred L. Drake,
Jr. Original navigation icons were contributed by Christopher
Petrilli.
---
## Comments and Questions
General comments and questions regarding this document should
be sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in
this document, please report the bug at the Python Bug
Tracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).
Questions regarding how to use the information in this
document should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and
carries the same content).
For any of these channels, please be sure not to send HTML email.
Thanks.
---
genindex.html | ref.html | Python Reference Manual | contents.html | genindex.html
---


6.2 Assert statements

exprstmts.html | simple.html | assignment.html | Python Reference Manual | contents.html | genindex.html
---
# 6.2 Assert statements
Assert statements are a convenient way to insert
debugging assertions into a program:
```text

assert_statement: "assert" expression ["," expression]
```
The simple form, "assert expression", is equivalent to
```text

if __debug__:
if not expression: raise AssertionError
```
The extended form, "assert expression1, expression2", is
equivalent to
```text

if __debug__:
if not expression1: raise AssertionError, expression2
```
These equivalences assume that `__debug__` and
AssertionError refer to the built-in
variables with those names. In the current implementation, the
built-in variable `__debug__` is 1 under normal circumstances, 0
when optimization is requested (command line option -O). The current
code generator emits no code for an assert statement when optimization
is requested at compile time. Note that it is unnecessary to include
the source code for the expression that failed in the error message;
it will be displayed as part of the stack trace.


6.3 Assignment statements

assert.html | simple.html | pass.html | Python Reference Manual | contents.html | genindex.html
---
# 6.3 Assignment statements
Assignment statements are used to
(re)bind names to values and to modify attributes or items of mutable
objects:
```text

assignment_stmt: (target_list "=")+ expression_list
target_list: target ("," target)* [","]
target: identifier | "(" target_list ")" | "[" target_list "]"
| attributeref | subscription | slicing
```
(See section 5.3 (primaries.html#primaries) for the syntax definitions for the last
three symbols.)
An assignment statement evaluates the expression list (remember that
this can be a single expression or a comma-separated list, the latter
yielding a tuple) and assigns the single resulting object to each of
the target lists, from left to right.
Assignment is defined recursively depending on the form of the target
(list). When a target is part of a mutable object (an attribute
reference, subscription or slicing), the mutable object must
ultimately perform the assignment and decide about its validity, and
may raise an exception if the assignment is unacceptable. The rules
observed by various types and the exceptions raised are given with the
definition of the object types (see section 3.2 (types.html#types)).
Assignment of an object to a target list is recursively defined as
follows.
- If the target list is a single target: The object is assigned to that
target.
- If the target list is a comma-separated list of targets: The object
must be a sequence with the same number of items as the there are
targets in the target list, and the items are assigned, from left to
right, to the corresponding targets. (This rule is relaxed as of
Python 1.5; in earlier versions, the object had to be a tuple. Since
strings are sequences, an assignment like "a, b = "xy"" is
now legal as long as the string has the right length.)
Assignment of an object to a single target is recursively defined as
follows.
- If the target is an identifier (name):
- If the name does not occur in a global statement in the current
code block: the name is bound to the object in the current local
namespace.
- Otherwise: the name is bound to the object in the current global
namespace.
The name is rebound if it was already bound. This may cause the
reference count for the object previously bound to the name to reach
zero, causing the object to be deallocated and its
destructor (if it has one) to be called.
- If the target is a target list enclosed in parentheses or in square
brackets: The object must be a sequence with the same number of items
as there are targets in the target list, and its items are assigned,
from left to right, to the corresponding targets.
- If the target is an attribute reference: The primary expression in the
reference is evaluated. It should yield an object with assignable
attributes; if this is not the case, TypeError is raised. That
object is then asked to assign the assigned object to the given
attribute; if it cannot perform the assignment, it raises an exception
(usually but not necessarily AttributeError).
- If the target is a subscription: The primary expression in the
reference is evaluated. It should yield either a mutable sequence
object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
the subscript expression is evaluated.
If the primary is a mutable sequence object (e.g., a list), the subscript
must yield a plain integer. If it is negative, the sequence's length
is added to it. The resulting value must be a nonnegative integer
less than the sequence's length, and the sequence is asked to assign
the assigned object to its item with that index. If the index is out
of range, IndexError is raised (assignment to a subscripted
sequence cannot add new items to a list).
If the primary is a mapping object (e.g., a dictionary), the subscript must
have a type compatible with the mapping's key type, and the mapping is
then asked to create a key/datum pair which maps the subscript to
the assigned object. This can either replace an existing key/value
pair with the same key value, or insert a new key/value pair (if no
key with the same value existed).
- If the target is a slicing: The primary expression in the reference is
evaluated. It should yield a mutable sequence object (e.g., a list). The
assigned object should be a sequence object of the same type. Next,
the lower and upper bound expressions are evaluated, insofar they are
present; defaults are zero and the sequence's length. The bounds
should evaluate to (small) integers. If either bound is negative, the
sequence's length is added to it. The resulting bounds are clipped to
lie between zero and the sequence's length, inclusive. Finally, the
sequence object is asked to replace the slice with the items of the
assigned sequence. The length of the slice may be different from the
length of the assigned sequence, thus changing the length of the
target sequence, if the object allows it.
(In the current implementation, the syntax for targets is taken
to be the same as for expressions, and invalid syntax is rejected
during the code generation phase, causing less detailed error
messages.)
WARNING: Although the definition of assignment implies that overlaps
between the left-hand side and the right-hand side are `safe' (e.g.,
"a, b = b, a" swaps two variables), overlaps within the
collection of assigned-to variables are not safe! For instance, the
following program prints "[0, 2]":
```text

x = [0, 1]
i = 0
i, x[i] = 1, 2
print x
```


5.2.1 Identifiers (Names)

atoms.html | atoms.html | atom-literals.html | Python Reference Manual | contents.html | genindex.html
---
## 5.2.1 Identifiers (Names)
An identifier occurring as an atom is a reference to a local, global
or built-in name binding. If a name is assigned to anywhere in a code
block (even in unreachable code), and is not mentioned in a
global statement in that code block, then it refers to a local
name throughout that code block. When it is not assigned to anywhere
in the block, or when it is assigned to but also explicitly listed in
a global statement, it refers to a global name if one exists,
else to a built-in name (and this binding may dynamically change).
When the name is bound to an object, evaluation of the atom yields
that object. When a name is not bound, an attempt to evaluate it
raises a NameError exception.
Private name mangling:when an identifier that textually occurs in a class definition begins
with two or more underscore characters and does not end in two or more
underscores, it is considered a private name of that class.
Private names are transformed to a longer form before code is
generated for them. The transformation inserts the class name in
front of the name, with leading underscores removed, and a single
underscore inserted in front of the class name. For example, the
identifier `__spam` occurring in a class named `Ham` will be
transformed to `_Ham__spam`. This transformation is independent
of the syntactical context in which the identifier is used. If the
transformed name is extremely long (longer than 255 characters),
implementation defined truncation may happen. If the class name
consists only of underscores, no transformation is done.


5.2.2 Literals

atom-identifiers.html | atoms.html | parenthesized.html | Python Reference Manual | contents.html | genindex.html
---
## 5.2.2 Literals
Python supports string literals and various numeric literals:
```text

literal: stringliteral | integer | longinteger | floatnumber | imagnumber
```
Evaluation of a literal yields an object of the given type (string,
integer, long integer, floating point number, complex number) with the
given value. The value may be approximated in the case of floating
point and imaginary (complex) literals. See section 2.4 (literals.html#literals)
for details.
All literals correspond to immutable data types, and hence the
object's identity is less important than its value. Multiple
evaluations of literals with the same value (either the same
occurrence in the program text or a different occurrence) may obtain
the same object or a different object with the same value.


5.2 Atoms

conversions.html | expressions.html | atom-identifiers.html | Python Reference Manual | contents.html | genindex.html
---
# 5.2 Atoms
Atoms are the most basic elements of expressions. The simplest atoms
are identifiers or literals. Forms enclosed in
reverse quotes or in parentheses, brackets or braces are also
categorized syntactically as atoms. The syntax for atoms is:
```text

atom: identifier | literal | enclosure
enclosure: parenth_form|list_display|dict_display|string_conversion
```


3.3.2 Customizing attribute access

customization.html | specialnames.html | callable-types.html | Python Reference Manual | contents.html | genindex.html
---
## 3.3.2 Customizing attribute access
The following methods can be defined to customize the meaning of
attribute access (use of, assignment to, or deletion of `x.name`)
for class instances.
For performance reasons, these methods are cached in the class object
at class definition time; therefore, they cannot be changed after the
class definition is executed.


5.3.1 Attribute references

primaries.html | primaries.html | subscriptions.html | Python Reference Manual | contents.html | genindex.html
---
## 5.3.1 Attribute references
An attribute reference is a primary followed by a period and a name:
```text

attributeref: primary "." identifier
```
The primary must evaluate to an object of a type that supports
attribute references, e.g., a module or a list. This object is then
asked to produce the attribute whose name is the identifier. If this
attribute is not available, the exception
AttributeError is raised.
Otherwise, the type and value of the object produced is determined by
the object. Multiple evaluations of the same attribute reference may
yield different objects.


5.6 Binary arithmetic operations

unary.html | expressions.html | shifting.html | Python Reference Manual | contents.html | genindex.html
---
# 5.6 Binary arithmetic operations
The binary arithmetic operations have the conventional priority
levels. Note that some of these operations also apply to certain
non-numeric types. Apart from the power operator, there are only two
levels, one for multiplicative operators and one for additive
operators:
```text

m_expr: u_expr | m_expr "*" u_expr
| m_expr "/" u_expr | m_expr "%" u_expr
a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
```
The `*` (multiplication) operator yields the product of its
arguments. The arguments must either both be numbers, or one argument
must be a plain integer and the other must be a sequence. In the
former case, the numbers are converted to a common type and then
multiplied together. In the latter case, sequence repetition is
performed; a negative repetition factor yields an empty sequence.
The `/` (division) operator yields the quotient of its
arguments. The numeric arguments are first converted to a common
type. Plain or long integer division yields an integer of the same
type; the result is that of mathematical division with the `floor'
function applied to the result. Division by zero raises the
ZeroDivisionError exception.
The `%` (modulo) operator yields the remainder from the
division of the first argument by the second. The numeric arguments
are first converted to a common type. A zero right argument raises
the ZeroDivisionError exception. The arguments may be floating
point numbers, e.g., `3.14%0.7` equals `0.34` (since
`3.14` equals `4*0.7 + 0.34`.) The modulo operator always
yields a result with the same sign as its second operand (or zero);
the absolute value of the result is strictly smaller than the second
operand.
The integer division and modulo operators are connected by the
following identity: `x == (x/y)*y + (x%y)`. Integer division and
modulo are also connected with the built-in function divmod():
`divmod(x, y) == (x/y, x%y)`. These identities don't hold for
floating point and complex numbers; there similar identities hold
approximately where `x/y` is replaced by `floor(x/y)`) or
`floor(x/y) - 1` (for floats),5.1 (#foot3338) or `floor((x/y).real)` (for
complex).
The `+` (addition) operator yields the sum of its arguments.
The arguments must either both be numbers or both sequences of the
same type. In the former case, the numbers are converted to a common
type and then added together. In the latter case, the sequences are
concatenated.
The `-` (subtraction) operator yields the difference of its
arguments. The numeric arguments are first converted to a common
type.


5.8 Binary bit-wise operations

shifting.html | expressions.html | comparisons.html | Python Reference Manual | contents.html | genindex.html
---
# 5.8 Binary bit-wise operations
Each of the three bitwise operations has a different priority level:
```text

and_expr: shift_expr | and_expr "&" shift_expr
xor_expr: and_expr | xor_expr "^" and_expr
or_expr: xor_expr | or_expr "|" xor_expr
```
The `&` operator yields the bitwise AND of its arguments, which
must be plain or long integers. The arguments are converted to a
common type.
The `^` operator yields the bitwise XOR (exclusive OR) of its
arguments, which must be plain or long integers. The arguments are
converted to a common type.
The `|` operator yields the bitwise (inclusive) OR of its
arguments, which must be plain or long integers. The arguments are
converted to a common type.


2.1.6 Blank lines

implicit-joining.html | line-structure.html | indentation.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.6 Blank lines
A logical line that contains only spaces, tabs, formfeeds and possibly
a comment, is ignored (i.e., no NEWLINE token is generated). During
interactive input of statements, handling of a blank line may differ
depending on the implementation of the read-eval-print loop. In the
standard implementation, an entirely blank logical line (i.e. one
containing not even whitespace or a comment) terminates a multi-line
statement.


6.9 The break statement

raise.html | simple.html | continue.html | Python Reference Manual | contents.html | genindex.html
---
# 6.9 The break statement
```text

break_stmt: "break"
```
break may only occur syntactically nested in a for
or while loop, but not nested in a function or class definition
within that loop.
It terminates the nearest enclosing loop, skipping the optional
else clause if the loop has one.
If a for loop is terminated by break, the loop control
target keeps its current value.
When break passes control out of a try statement
with a finally clause, that finally clause is executed
before really leaving the loop.


3.3.3 Emulating callable objects

attribute-access.html | specialnames.html | sequence-types.html | Python Reference Manual | contents.html | genindex.html
---
## 3.3.3 Emulating callable objects


5.3.4 Calls

slicings.html | primaries.html | power.html | Python Reference Manual | contents.html | genindex.html
---
## 5.3.4 Calls
A call calls a callable object (e.g., a function) with a possibly empty
series of arguments:
```text

call: primary "(" [argument_list [","]] ")"
argument_list: positional_arguments ["," keyword_arguments]
| keyword_arguments
positional_arguments: expression ("," expression)*
keyword_arguments: keyword_item ("," keyword_item)*
keyword_item: identifier "=" expression
```
A trailing comma may be present after an argument list but does not
affect the semantics.
The primary must evaluate to a callable object (user-defined
functions, built-in functions, methods of built-in objects, class
objects, methods of class instances, and certain class instances
themselves are callable; extensions may define additional callable
object types). All argument expressions are evaluated before the call
is attempted. Please refer to section 7.5 (function.html#function) for the syntax
of formal parameter lists.
If keyword arguments are present, they are first converted to
positional arguments, as follows. First, a list of unfilled slots is
created for the formal parameters. If there are N positional
arguments, they are placed in the first N slots. Next, for each
keyword argument, the identifier is used to determine the
corresponding slot (if the identifier is the same as the first formal
parameter name, the first slot is used, and so on). If the slot is
already filled, a TypeError exception is raised.
Otherwise, the value of the argument is placed in the slot, filling it
(even if the expression is `None`, it fills the slot). When all
arguments have been processed, the slots that are still unfilled are
filled with the corresponding default value from the function
definition. (Default values are calculated, once, when the function
is defined; thus, a mutable object such as a list or dictionary used
as default value will be shared by all calls that don't specify an
argument value for the corresponding slot; this should usually be
avoided.) If there are any unfilled slots for which no default value
is specified, a TypeError exception is raised. Otherwise,
the list of filled slots is used as the argument list for the call.
If there are more positional arguments than there are formal parameter
slots, a TypeError exception is raised, unless a formal
parameter using the syntax "*identifier" is present; in this
case, that formal parameter receives a tuple containing the excess
positional arguments (or an empty tuple if there were no excess
positional arguments).
If any keyword argument does not correspond to a formal parameter
name, a TypeError exception is raised, unless a formal
parameter using the syntax "**identifier" is present; in this
case, that formal parameter receives a dictionary containing the
excess keyword arguments (using the keywords as keys and the argument
values as corresponding values), or a (new) empty dictionary if there
were no excess keyword arguments.
Formal parameters using the syntax "*identifier" or
"**identifier" cannot be used as positional argument slots or
as keyword argument names. Formal parameters using the syntax
"(sublist)" cannot be used as keyword argument names; the
outermost sublist corresponds to a single unnamed argument slot, and
the argument value is assigned to the sublist using the usual tuple
assignment rules after all other parameter processing is done.
A call always returns some value, possibly `None`, unless it
raises an exception. How this value is computed depends on the type
of the callable object.
If it is--
a user-defined function:: The code block for the function is
executed, passing it the argument list. The first thing the code
block will do is bind the formal parameters to the arguments; this is
described in section 7.5 (function.html#function). When the code block executes a
return statement, this specifies the return value of the
function call.
a built-in function or method:: The result is up to the
interpreter; see the library reference manual for the descriptions of
built-in functions and methods.
a class object:: A new instance of that class is returned.
a class instance method:: The corresponding user-defined
function is called, with an argument list that is one longer than the
argument list of the call: the instance becomes the first argument.
a class instance:: The class must define a __call__()
method; the effect is then the same as if that method was called.


7.6 Class definitions

function.html | compound.html | top-level.html | Python Reference Manual | contents.html | genindex.html
---
# 7.6 Class definitions
A class definition defines a class object (see section 3.2 (types.html#types)):
```text

classdef: "class" classname [inheritance] ":" suite
inheritance: "(" [expression_list] ")"
classname: identifier
```
A class definition is an executable statement. It first evaluates the
inheritance list, if present. Each item in the inheritance list
should evaluate to a class object. The class's suite is then executed
in a new execution frame (see section 4.1 (execframes.html#execframes)), using a newly
created local namespace and the original global namespace.
(Usually, the suite contains only function definitions.) When the
class's suite finishes execution, its execution frame is discarded but
its local namespace is saved. A class object is then created using
the inheritance list for the base classes and the saved local
namespace for the attribute dictionary. The class name is bound to this
class object in the original local namespace.


2.1.3 Comments

physical.html | line-structure.html | explicit-joining.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.3 Comments
A comment starts with a hash character (`#`) that is not part of
a string literal, and ends at the end of the physical line. A comment
signifies the end of the logical line unless the implicit line joining
rules are invoked.
Comments are ignored by the syntax; they are not tokens.


5.9 Comparisons

bitwise.html | expressions.html | lambda.html | Python Reference Manual | contents.html | genindex.html
---
# 5.9 Comparisons
Contrary to C, all comparison operations in Python have the same
priority, which is lower than that of any arithmetic, shifting or
bitwise operation. Also contrary to C, expressions like
`a < b < c` have the interpretation that is conventional in
mathematics:
```text

comparison: or_expr (comp_operator or_expr)*
comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
```
Comparisons yield integer values: `1` for true, `0` for false.
Comparisons can be chained arbitrarily, e.g., `x < y <= z` is
equivalent to `x < y and y <= z`, except that `y` is
evaluated only once (but in both cases `z` is not evaluated at all
when `x < y` is found to be false).
Formally, if a, b, c, ..., y, z are
expressions and opa, opb, ..., opy are comparison
operators, then a opa b opb c ...y opy z is equivalent
to a opa b and b opb c and ...
y opy z, except that each expression is evaluated at most once.
Note that a opa b opb c doesn't imply any kind of comparison
between a and c, so that, e.g., `x < y > z` is
perfectly legal (though perhaps not pretty).
The forms `<>` and `!=` are equivalent; for consistency with
C, `!=` is preferred; where `!=` is mentioned below
`<>` is also acceptable. At some point in the (far) future,
`<>` may become obsolete.
The operators "<", ">", "==", ">=", "<=", and "!=" compare
the values of two objects. The objects needn't have the same type.
If both are numbers, they are coverted to a common type. Otherwise,
objects of different types always compare unequal, and are
ordered consistently but arbitrarily.
(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and
not in operators. In the future, the comparison rules for
objects of different types are likely to change.)
Comparison of objects of the same type depends on the type:
- Numbers are compared arithmetically.
- Strings are compared lexicographically using the numeric equivalents
(the result of the built-in function ord()) of their
characters.
- Tuples and lists are compared lexicographically using comparison of
corresponding items.
- Mappings (dictionaries) are compared through lexicographic
comparison of their sorted (key, value) lists.5.2 (#foot3301)
- Most other types compare unequal unless they are the same object;
the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one
execution of a program.
The operators in and not in test for sequence
membership: if y is a sequence, `x in y` is
true if and only if there exists an index i such that
`x = y [ i ]`.
`x not in y` yields the inverse truth value. The
exception TypeError is raised when y is not a sequence,
or when y is a string and x is not a string of length
one.5.3 (#foot3122)
The operators is and is not test for object identity:
`x is y` is true if and only if x and y
are the same object. `x is not y` yields the inverse
truth value.


7. Compound statements

exec.html | ref.html | if.html | Python Reference Manual | contents.html | genindex.html
---
# 7. Compound statements
Compound statements contain (groups of) other statements; they affect
or control the execution of those other statements in some way. In
general, compound statements span multiple lines, although in simple
incarnations a whole compound statement may be contained in one line.
The if, while and for statements implement
traditional control flow constructs. try specifies exception
handlers and/or cleanup code for a group of statements. Function and
class definitions are also syntactically compound statements.
Compound statements consist of one or more `clauses.' A clause
consists of a header and a `suite.' The clause headers of a
particular compound statement are all at the same indentation level.
Each clause header begins with a uniquely identifying keyword and ends
with a colon. A suite is a group of statements controlled by a
clause. A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header's
colon, or it can be one or more indented statements on subsequent
lines. Only the latter form of suite can contain nested compound
statements; the following is illegal, mostly because it wouldn't be
clear to which if clause a following else clause would
belong:
```text

if test1: if test2: print x
```
Also note that the semicolon binds tighter than the colon in this
context, so that in the following example, either all or none of the
print statements are executed:
```text

if x < y < z: print x; print y; print z
```
Summarizing:
```text

compound_stmt: if_stmt | while_stmt | for_stmt
| try_stmt | funcdef | classdef
suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement: stmt_list NEWLINE | compound_stmt
stmt_list: simple_stmt (";" simple_stmt)* [";"]
```
Note that statements always end in a
`NEWLINE` possibly followed by a
`DEDENT`. Also note that optional
continuation clauses always begin with a keyword that cannot start a
statement, thus there are no ambiguities (the `dangling
else' problem is solved in Python by requiring nested
if statements to be indented).
The formatting of the grammar rules in the following sections places
each clause on a separate line for clarity.


Contents

front.html | ref.html | introduction.html | Python Reference Manual | genindex.html
---
## Contents


6.10 The continue statement

break.html | simple.html | import.html | Python Reference Manual | contents.html | genindex.html
---
# 6.10 The continue statement
```text

continue_stmt: "continue"
```
continue may only occur syntactically nested in a for or
while loop, but not nested in a function or class definition or
try statement within that loop.6.1 (#foot4241)It continues with the next cycle of the nearest enclosing loop.


5.1 Arithmetic conversions

expressions.html | expressions.html | atoms.html | Python Reference Manual | contents.html | genindex.html
---
# 5.1 Arithmetic conversions
When a description of an arithmetic operator below uses the phrase
``the numeric arguments are converted to a common type,'' the
arguments are coerced using the coercion rules listed at the end of
chapter 3. If both arguments are standard numeric types, the
following coercions are applied:
- If either argument is a complex number, the other is converted
to complex;
- otherwise, if either argument is a floating point number,
the other is converted to floating point;
- otherwise, if either argument is a long integer,
the other is converted to long integer;
- otherwise, both must be plain integers and no conversion
is necessary.
Some additional rules apply for certain operators (e.g., a string left
argument to the `%' operator). Extensions can define their own
coercions.


3.3.1 Basic customization

specialnames.html | specialnames.html | attribute-access.html | Python Reference Manual | contents.html | genindex.html
---
## 3.3.1 Basic customization


3. Data model

delimiters.html | ref.html | objects.html | Python Reference Manual | contents.html | genindex.html
---
# 3. Data model


6.5 The del statement

pass.html | simple.html | print.html | Python Reference Manual | contents.html | genindex.html
---
# 6.5 The del statement
```text

del_stmt: "del" target_list
```
Deletion is recursively defined very similar to the way assignment is
defined. Rather that spelling it out in full details, here are some
hints.
Deletion of a target list recursively deletes each target, from left
to right.
Deletion of a name removes the binding of that name (which must exist)
from the local or global namespace, depending on whether the name
occurs in a global statement in the same code block.
Deletion of attribute references, subscriptions and slicings
is passed to the primary object involved; deletion of a slicing
is in general equivalent to assignment of an empty slice of the
right type (but even this is determined by the sliced object).


2.6 Delimiters

operators.html | lexical.html | datamodel.html | Python Reference Manual | contents.html | genindex.html
---
# 2.6 Delimiters
The following tokens serve as delimiters in the grammar:
```text

( ) [ ] { }
, : . ` = ;
```
The period can also occur in floating-point and imaginary literals. A
sequence of three periods has a special meaning as an ellipsis in slices.
The following printing ASCII characters have special meaning as part
of other tokens or are otherwise significant to the lexical analyzer:
```text

' " # \
```
The following printing ASCII characters are not used in Python. Their
occurrence outside string literals and comments is an unconditional
error:


5.2.5 Dictionary displays

lists.html | atoms.html | string-conversions.html | Python Reference Manual | contents.html | genindex.html
---
## 5.2.5 Dictionary displays
A dictionary display is a possibly empty series of key/datum pairs
enclosed in curly braces:
```text

dict_display: "{" [key_datum_list] "}"
key_datum_list: key_datum ("," key_datum)* [","]
key_datum: expression ":" expression
```
A dictionary display yields a new dictionary object.
The key/datum pairs are evaluated from left to right to define the
entries of the dictionary: each key object is used as a key into the
dictionary to store the corresponding datum.
Restrictions on the types of the key values are listed earlier in
section 3.2 (types.html#types). (To summarize,the key type should be hashable,
which excludes all mutable objects.) Clashes between duplicate keys
are not detected; the last datum (textually rightmost in the display)
stored for a given key value prevails.


4.2 Exceptions

execframes.html | execmodel.html | expressions.html | Python Reference Manual | contents.html | genindex.html
---
# 4.2 Exceptions
Exceptions are a means of breaking out of the normal flow of control
of a code block in order to handle errors or other exceptional
conditions. An exception is
raised at the point where the error
is detected; it may be handled by
the surrounding code block or by any code block that directly or
indirectly invoked the code block where the error occurred.
The Python interpreter raises an exception when it detects a run-time
error (such as division by zero). A Python program can also
explicitly raise an exception with the raise statement.
Exception handlers are specified with the try ... except
statement. The try ... finally statement
specifies cleanup code which does not handle the exception, but is
executed whether an exception occurred or not in the preceding code.
Python uses the ``termination'' model of
error handling: an exception handler can find out what happened and
continue execution at an outer level, but it cannot repair the cause
of the error and retry the failing operation (except by re-entering
the offending piece of code from the top).
When an exception is not handled at all, the interpreter terminates
execution of the program, or returns to its interactive main loop. In
either case, it prints a stack backtrace, except when the exception is
SystemExit.
Exceptions are identified by string objects or class instances.
Selection of a matching except clause is based on object identity
(i.e., two different string objects with the same value represent
different exceptions!) For string exceptions, the except
clause must reference the same string object. For class exceptions,
the except clause must reference the same class or a base
class of it.
When an exception is raised, an object (maybe `None`) is passed
as the exception's ``parameter'' or ``value''; this object does not
affect the selection of an exception handler, but is passed to the
selected exception handler as additional information. For class
exceptions, this object must be an instance of the exception class
being raised.


6.13 The exec statement

global.html | simple.html | compound.html | Python Reference Manual | contents.html | genindex.html
---
# 6.13 The exec statement
```text

exec_stmt: "exec" expression ["in" expression ["," expression]]
```
This statement supports dynamic execution of Python code. The first
expression should evaluate to either a string, an open file object, or
a code object. If it is a string, the string is parsed as a suite of
Python statements which is then executed (unless a syntax error
occurs). If it is an open file, the file is parsed until EOF and
executed. If it is a code object, it is simply executed.
In all cases, if the optional parts are omitted, the code is executed
in the current scope. If only the first expression after in
is specified, it should be a dictionary, which will be used for both
the global and the local variables. If two expressions are given,
both must be dictionaries and they are used for the global and local
variables, respectively.
As a side effect, an implementation may insert additional keys into
the dictionaries given besides those corresponding to variable names
set by the executed code. For example, the current implementation
may add a reference to the dictionary of the built-in module
__builtin__ under the key `__builtins__` (!).
Programmer's hints:
dynamic evaluation of expressions is supported by the built-in
function eval(). The built-in functions
globals() and locals() return the current global
and local dictionary, respectively, which may be useful to pass around
for use by exec.
Also, in the current implementation, multi-line compound statements must
end with a newline:
`exec "for v in seq:\n\tprint v\n"` works, but
`exec "for v in seq:\n\tprint v"` fails with
SyntaxError.


execmodel.html | execmodel.html | exceptions.html | Python Reference Manual | contents.html | genindex.html
---
# 4.1 Code blocks, execution frames, and namespaces
A code block is a piece
of Python program text that can be executed as a unit, such as a
module, a class definition or a function body. Some code blocks (like
modules) are normally executed only once, others (like function
bodies) may be executed many times. Code blocks may textually contain
other code blocks. Code blocks may invoke other code blocks (that may
or may not be textually contained in them) as part of their execution,
e.g., by invoking (calling) a function.
The following are code blocks: A module is a code block. A function
body is a code block. A class definition is a code block. Each
command typed interactively is a separate code block; a script file (a
file given as standard input to the interpreter or specified on the
interpreter command line the first argument) is a code block; a script
command (a command specified on the interpreter command line with the
`-c' option) is a code block. The file read by the built-in
function execfile() is a code block. The string argument
passed to the built-in function eval() and to the
exec statement is a code block. And finally, the expression
read and evaluated by the built-in function input() is a
code block.
A code block is executed in an execution frame. An execution
frame contains some administrative
information (used for debugging), determines where and how execution
continues after the code block's execution has completed, and (perhaps
most importantly) defines two namespaces, the local and the global
namespace, that affect execution of the code block.
A namespace is a mapping from names
(identifiers) to objects. A particular namespace may be referenced by
more than one execution frame, and from other places as well. Adding
a name to a namespace is called binding a
name (to an object); changing the mapping of a name is called
rebinding; removing a name is
unbinding. Namespaces are functionally
equivalent to dictionaries (and often implemented as dictionaries).
The local namespace of an execution
frame determines the default place where names are defined and
searched. The
global namespace determines the place
where names listed in global statements are
defined and searched, and where names that are not bound anywhere in
the current code block are searched.
Whether a name is local or global in a code block is determined by
static inspection of the source text for the code block: in the
absence of global statements, a name that is bound anywhere
in the code block is local in the entire code block; all other names
are considered global. The global statement forces global
interpretation of selected names throughout the code block. The
following constructs bind names: formal parameters to functions,
import statements, class and function definitions (these
bind the class or function name in the defining block), and targets
that are identifiers if occurring in an assignment, for loop
header, or in the second position of an except clause
header. Local names are searched only on the local namespace; global
names are searched only in the global and built-in
namespace.4.1 (#foot2677)
A target occurring in a del statement is also considered bound
for this purpose (though the actual semantics are to ``unbind'' the
name).
When a global name is not found in the global namespace, it is
searched in the built-in namespace (which is actually the global
namespace of the module
__builtin__). The built-in
namespace associated with the execution of a code block is actually
found by looking up the name `__builtins__` is its global
namespace; this should be a dictionary or a module (in the latter case
its dictionary is used). Normally, the `__builtins__` namespace
is the dictionary of the built-in module __builtin__ (note:
no `s'); if it isn't, restricted
execution mode is in effect. When a
name is not found at all, a
NameError exception is raised.
The following table lists the meaning of the local and global
namespace for various types of code blocks. The namespace for a
particular module is automatically created when the module is first
imported (i.e., when it is loaded). Note that in almost all cases,
the global namespace is the namespace of the containing module --
scopes in Python do not nest!
Notes:
n.s.: means namespace
(1): The main module for a script is always called
__main__; ``the filename don't enter into it.''
(2): The global and local namespace for these can be
overridden with optional extra arguments.
(3): The exec statement and the eval() and
execfile() functions have optional arguments to override
the global and local namespace. If only one namespace is specified,
it is used for both.
The built-in functions globals() and locals() returns a
dictionary representing the current global and local namespace,
respectively. The effect of modifications to this dictionary on the
namespace are undefined.4.2 (#foot2685)


4. Execution model

numeric-types.html | ref.html | execframes.html | Python Reference Manual | contents.html | genindex.html
---
# 4. Execution model


2.1.4 Explicit line joining

comments.html | line-structure.html | implicit-joining.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.4 Explicit line joining
Two or more physical lines may be joined into logical lines using
backslash characters (`\`), as follows: when a physical line ends
in a backslash that is not part of a string literal or comment, it is
joined with the following forming a single logical line, deleting the
backslash and the following end-of-line character. For example:
```text

if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
return 1
```
A line ending in a backslash cannot carry a comment. A backslash does
not continue a comment. A backslash does not continue a token except
for string literals (i.e., tokens other than string literals cannot be
split across physical lines using a backslash). A backslash is
illegal elsewhere on a line outside a string literal.


8.4 Expression input

interactive.html | top-level.html | genindex.html | Python Reference Manual | contents.html | genindex.html
---
# 8.4 Expression input
There are two forms of expression input. Both ignore leading
whitespace.
The string argument to eval() must have the following form:
```text

eval_input: expression_list NEWLINE*
```
The input line read by input() must have the following form:
```text

input_input: expression_list NEWLINE
```
Note: to read `raw' input line without interpretation, you can use the
built-in function raw_input() or the readline() method
of file objects.


5. Expressions

exceptions.html | ref.html | conversions.html | Python Reference Manual | contents.html | genindex.html
---
# 5. Expressions
This chapter explains the meaning of the elements of expressions in
Python.
Syntax Notes: In this and the following chapters, extended
BNF notation will be used to describe syntax, not lexical
analysis. When (one alternative of) a syntax rule has the form
```text

name: othername
```
and no semantics are given, the semantics of this form of `name`are the same as for `othername`.


5.11 Expression lists

lambda.html | expressions.html | summary.html | Python Reference Manual | contents.html | genindex.html
---
# 5.11 Expression lists
```text

expression_list: expression ("," expression)* [","]
```
An expression list containing at least one comma yields a
tuple. The length of the tuple is the number of expressions in the
list. The expressions are evaluated from left to right.
The trailing comma is required only to create a single tuple (a.k.a. a
singleton); it is optional in all other cases. A single
expression without a trailing comma doesn't create a
tuple, but rather yields the value of that expression.
(To create an empty tuple, use an empty pair of parentheses:
`()`.)


6.1 Expression statements

simple.html | simple.html | assert.html | Python Reference Manual | contents.html | genindex.html
---
# 6.1 Expression statements
Expression statements are used (mostly interactively) to compute and
write a value, or (usually) to call a procedure (a function that
returns no meaningful result; in Python, procedures return the value
`None`). Other uses of expression statements are allowed and
occasionally useful. The syntax for an expression statement is:
```text

expression_stmt: expression_list
```
An expression statement evaluates the expression list (which may be a
single expression).
In interactive mode, if the value is not `None`, it is converted
to a string using the built-in repr()
function and the resulting string is written to standard output (see
section 6.6 (print.html#print)) on a line by itself. (Expression statements
yielding None are not written, so that procedure calls do not cause
any output.)


8.2 File input

programs.html | top-level.html | interactive.html | Python Reference Manual | contents.html | genindex.html
---
# 8.2 File input
All input read from non-interactive files has the same form:
```text

file_input: (NEWLINE | statement)*
```
This syntax is used in the following situations:
- when parsing a complete Python program (from a file or from a string);
- when parsing a module;
- when parsing a string passed to the exec statement;


2.4.5 Floating point literals

integers.html | literals.html | imaginary.html | Python Reference Manual | contents.html | genindex.html
---
## 2.4.5 Floating point literals
Floating point literals are described by the following lexical
definitions:
```text

floatnumber: pointfloat | exponentfloat
pointfloat: [intpart] fraction | intpart "."
exponentfloat: (nonzerodigit digit* | pointfloat) exponent
intpart: nonzerodigit digit* | "0"
fraction: "." digit+
exponent: ("e"|"E") ["+"|"-"] digit+
```
Note that the integer part of a floating point number cannot look like
an octal integer, though the exponent may look like an octal literal
but will always be interpreted using radix 10. For example,
"1e010" is legal, while "07.1" is a syntax error.
The allowed range of floating point literals is
implementation-dependent.
Some examples of floating point literals:
```text

3.14 10. .001 1e100 3.14e-10
```
Note that numeric literals do not include a sign; a phrase like
`-1` is actually an expression composed of the operator
`-` and the literal `1`.


7.3 The for statement

while.html | compound.html | try.html | Python Reference Manual | contents.html | genindex.html
---
# 7.3 The for statement
The for statement is used to iterate over the elements of a
sequence (string, tuple or list):
```text

for_stmt: "for" target_list "in" expression_list ":" suite
["else" ":" suite]
```
The expression list is evaluated once; it should yield a sequence. The
suite is then executed once for each item in the sequence, in the
order of ascending indices. Each item in turn is assigned to the
target list using the standard rules for assignments, and then the
suite is executed. When the items are exhausted (which is immediately
when the sequence is empty), the suite in the else clause, if
present, is executed, and the loop terminates.
A break statement executed in the first suite terminates the
loop without executing the else clause's suite. A
continue statement executed in the first suite skips the rest
of the suite and continues with the next item, or with the else
clause if there was no next item.
The suite may assign to the variable(s) in the target list; this does
not affect the next item assigned to it.
The target list is not deleted when the loop is finished, but if the
sequence is empty, it will not have been assigned to at all by the
loop. Hint: the built-in function range() returns a
sequence of integers suitable to emulate the effect of Pascal's
`for i := a to b do`;
e.g., `range(3)` returns the list `[0, 1, 2]`.
Warning: There is a subtlety when the sequence is being modified
by the loop (this can only occur for mutable sequences, i.e. lists).
An internal counter is used to keep track of which item is used next,
and this is incremented on each iteration. When this counter has
reached the length of the sequence the loop terminates. This means that
if the suite deletes the current (or a previous) item from the
sequence, the next item will be skipped (since it gets the index of
the current item which has already been treated). Likewise, if the
suite inserts an item in the sequence before the current item, the
current item will be treated again the next time through the loop.
This can lead to nasty bugs that can be avoided by making a temporary
copy using a slice of the whole sequence, e.g.,
```text

for x in a[:]:
if x < 0: a.remove(x)
```


Front Matter

ref.html | ref.html | contents.html | Python Reference Manual | contents.html | genindex.html
---
# Front Matter
BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization (``Licensee'') accessing and otherwise
using this software in source or binary form and its associated
documentation (``the Software'').
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an ``AS IS''
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the ``BeOpen Python'' logos available
at http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI OPEN SOURCE LICENSE AGREEMENT
Python 1.6 is made available subject to the terms and conditions in
CNRI's License Agreement. This Agreement together with Python 1.6 may
be located on the Internet using the following unique, persistent
identifier (known as a handle): 1895.22/1012. This Agreement may also
be obtained from a proxy server on the Internet using the following
URL: http://hdl.handle.net/1895.22/1012.
CWI PERMISSIONS STATEMENT AND DISCLAIMER
Copyright © 1991 - 1995, Stichting Mathematisch Centrum
Amsterdam, The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
### Abstract:
Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics. Its high-level built in data
structures, combined with dynamic typing and dynamic binding, make it
very attractive for rapid application development, as well as for use
as a scripting or glue language to connect existing components
together. Python's simple, easy to learn syntax emphasizes
readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages
program modularity and code reuse. The Python interpreter and the
extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
This reference manual describes the syntax and ``core semantics'' of
the language. It is terse, but attempts to be exact and complete.
The semantics of non-essential built-in object types and of the
built-in functions and modules are described in the
Python Library Reference (../lib/lib.html). For an
informal introduction to the language, see the
Python Tutorial (../tut/tut.html). For C or
C++ programmers, two additional manuals exist:
Extending and Embedding the Python
Interpreter (../ext/ext.html) describes the high-level picture of how to write a Python
extension module, and the Python/C API
Reference Manual (../api/api.html) describes the interfaces available to
C/C++ programmers in detail.


7.5 Function definitions

try.html | compound.html | class.html | Python Reference Manual | contents.html | genindex.html
---
# 7.5 Function definitions
A function definition defines a user-defined function object (see
section 3.2 (types.html#types)):
```text

funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier]
| "**" identifier
| defparameter [","])
defparameter: parameter ["=" expression]
sublist: parameter ("," parameter)* [","]
parameter: identifier | "(" sublist ")"
funcname: identifier
```
A function definition is an executable statement. Its execution binds
the function name in the current local namespace to a function object
(a wrapper around the executable code for the function). This
function object contains a reference to the current global namespace
as the global namespace to be used when the function is called.
The function definition does not execute the function body; this gets
executed only when the function is called.
When one or more top-level parameters have the form parameter
`=` expression, the function is said to have ``default
parameter values.'' For a parameter with a
default value, the corresponding argument may be omitted from a call,
in which case the parameter's default value is substituted. If a
parameter has a default value, all following parameters must also have
a default value -- this is a syntactic restriction that is not
expressed by the grammar.
Default parameter values are evaluated when the function
definition is executed. This means that the expression is evaluated
once, when the function is defined, and that that same
``pre-computed'' value is used for each call. This is especially
important to understand when a default parameter is a mutable object,
such as a list or a dictionary: if the function modifies the object
(e.g. by appending an item to a list), the default value is in effect
modified. This is generally not what was intended. A way around this
is to use `None` as the default, and explicitly test for it in
the body of the function, e.g.:
```text

def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = []
penguin.append("property of the zoo")
return penguin
```
Function call semantics are described in more detail in section
5.3.4 (calls.html#calls).
A function call always assigns values to all parameters mentioned in
the parameter list, either from position arguments, from keyword
arguments, or from default values. If the form ```*identifier`''
is present, it is initialized to a tuple receiving any excess
positional parameters, defaulting to the empty tuple. If the form
```**identifier`'' is present, it is initialized to a new
dictionary receiving any excess keyword arguments, defaulting to a
new empty dictionary.

It is also possible to create anonymous functions (functions not bound
to a name), for immediate use in expressions. This uses lambda forms,
described in section 5.10 (lambda.html#lambda). Note that the lambda form is
merely a shorthand for a simplified function definition; a function
defined in a ``def'' statement can be passed around or
assigned to another name just like a function defined by a lambda
form. The ``def'' form is actually more powerful since it
allows the execution of multiple statements.

Programmer's note: a ```def`'' form executed inside a
function definition defines a local function that can be returned or
passed around. Because of Python's two-scope philosophy, a local
function defined in this way does not have access to the local
variables of the function that contains its definition; the same rule
applies to functions defined by a lambda form. A standard trick to
pass selected local variables into a locally defined function is to
use default argument values, like this:

```text
# Return a function that returns its argument incremented by 'n'
def make_incrementer(n):
def increment(x, n=n):
return x+n
return increment
add1 = make_incrementer(1)
print add1(3) # This prints '4'
```


Index

expression-input.html | ref.html | about.html | Python Reference Manual | contents.html
---
## Index
---
_ (#letter-_) |
a (#letter-a) |
b (#letter-b) |
c (#letter-c) |
d (#letter-d) |
e (#letter-e) |
f (#letter-f) |
g (#letter-g) |
h (#letter-h) |
i (#letter-i) |
k (#letter-k) |
l (#letter-l) |
m (#letter-m) |
n (#letter-n) |
o (#letter-o) |
p (#letter-p) |
q (#letter-q) |
r (#letter-r) |
s (#letter-s) |
t (#letter-t) |
u (#letter-u) |
v (#letter-v) |
w (#letter-w) |
x (#letter-x) |
z (#letter-z)
---
## _ (underscore)
---
## A
---
## B
---
## C
---
## D
---
## E
---
## F
---
## G
---
## H
---
## I
---
## K
---
## L
---
## M
---
## N
---
## O
---
## P
---
## Q
---
## R
---
## S
---
## T
---
## U
---
## V
---
## W
---
## X
---
## Z


6.12 The global statement

import.html | simple.html | exec.html | Python Reference Manual | contents.html | genindex.html
---
# 6.12 The global statement
```text

global_stmt: "global" identifier ("," identifier)*
```
The global statement is a declaration which holds for the
entire current code block. It means that the listed identifiers are to be
interpreted as globals. While using global names is automatic
if they are not defined in the local scope, assigning to global
names would be impossible without global.
Names listed in a global statement must not be used in the same
code block textually preceding that global statement.
Names listed in a global statement must not be defined as formal
parameters or in a for loop control target, class
definition, function definition, or import statement.
(The current implementation does not enforce the latter two
restrictions, but programs should not abuse this freedom, as future
implementations may enforce them or silently change the meaning of the
program.)
Programmer's note:
the global is a directive to the parser. It
applies only to code parsed at the same time as the global
statement. In particular, a global statement contained in an
exec statement does not affect the code block containing
the exec statement, and code contained in an exec
statement is unaffected by global statements in the code
containing the exec statement. The same applies to the
eval(), execfile() and compile() functions.


2.3.2 Reserved classes of identifiers

keywords.html | identifiers.html | literals.html | Python Reference Manual | contents.html | genindex.html
---
## 2.3.2 Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special
meanings. These are:
(XXX need section references here.)
Note:
(1): The special identifier "_" is used in the interactive
interpreter to store the result of the last evaluation; it is stored
in the __builtin__ module. When not in interactive mode,
"_" has no special meaning and is not defined.


2.3 Identifiers and keywords

other-tokens.html | lexical.html | keywords.html | Python Reference Manual | contents.html | genindex.html
---
# 2.3 Identifiers and keywords
Identifiers (also referred to as names) are described by the following
lexical definitions:
```text

identifier: (letter|"_") (letter|digit|"_")*
letter: lowercase | uppercase
lowercase: "a"..."z"
uppercase: "A"..."Z"
digit: "0"..."9"
```
Identifiers are unlimited in length. Case is significant.


7.1 The if statement

compound.html | compound.html | while.html | Python Reference Manual | contents.html | genindex.html
---
# 7.1 The if statement
The if statement is used for conditional execution:
```text

if_stmt: "if" expression ":" suite
("elif" expression ":" suite)*
["else" ":" suite]
```
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section 5.10 (lambda.html#Booleans) for
the definition of true and false); then that suite is executed (and no
other part of the if statement is executed or evaluated). If
all expressions are false, the suite of the else clause, if
present, is executed.


2.4.6 Imaginary literals

floating.html | literals.html | operators.html | Python Reference Manual | contents.html | genindex.html
---
## 2.4.6 Imaginary literals
Imaginary literals are described by the following lexical definitions:
```text

imagnumber: (floatnumber | intpart) ("j"|"J")
```
An imaginary literal yields a complex number with a real part of
0.0. Complex numbers are represented as a pair of floating point
numbers and have the same restrictions on their range. To create a
complex number with a nonzero real part, add a floating point number
to it, e.g., `(3+4j)`. Some examples of imaginary literals:
```text

3.14j 10.j 10j .001j 1e100j 3.14e-10j
```


2.1.5 Implicit line joining

explicit-joining.html | line-structure.html | blank-lines.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.5 Implicit line joining
Expressions in parentheses, square brackets or curly braces can be
split over more than one physical line without using backslashes.
For example:
```text

month_names = ['Januari', 'Februari', 'Maart', # These are the
'April', 'Mei', 'Juni', # Dutch names
'Juli', 'Augustus', 'September', # for the months
'Oktober', 'November', 'December'] # of the year
```
Implicitly continued lines can carry comments. The indentation of the
continuation lines is not important. Blank continuation lines are
allowed. There is no NEWLINE token between implicit continuation
lines. Implicitly continued lines can also occur within triple-quoted
strings (see below); in that case they cannot carry comments.


6.11 The import statement

continue.html | simple.html | global.html | Python Reference Manual | contents.html | genindex.html
---
# 6.11 The import statement
```text

import_stmt: "import" module ("," module)*
| "from" module "import" identifier ("," identifier)*
| "from" module "import" "*"
module: (identifier ".")* identifier
```
Import statements are executed in two steps: (1) find a module, and
initialize it if necessary; (2) define a name or names in the local
namespace (of the scope where the import statement occurs).
The first form (without from) repeats these steps for each
identifier in the list. The form with from performs step
(1) once, and then performs step (2) repeatedly.
The system maintains a table of modules that have been initialized,
indexed by module name. This table table
accessible as `sys.modules`. When a module name is found in
this table, step (1) is finished. If not, a search for a module
definition is started. When a module is found, it is loaded. Details
of the module searching and loading process are implementation and
platform specific. It generally involves searching for a ``built-in''
module with the given name and then searching a list of locations
given as `sys.path`.
If a built-in module is found, its built-in initialization code is
executed and step (1) is finished. If no matching file is found,
ImportError is raised. If a file is found, it is parsed,
yielding an executable code block. If a syntax error occurs,
SyntaxError is raised. Otherwise, an empty module of the given
name is created and inserted in the module table, and then the code
block is executed in the context of this module. Exceptions during
this execution terminate step (1).
When step (1) finishes without raising an exception, step (2) can
begin.
The first form of import statement binds the module name in the
local namespace to the module object, and then goes on to import the
next identifier, if any. The from form does not bind the
module name: it goes through the list of identifiers, looks each one
of them up in the module found in step (1), and binds the name in the
local namespace to the object thus found. If a name is not found,
ImportError is raised. If the list of identifiers is replaced
by a star ("*"), all names defined in the module are bound,
except those beginning with an underscore ("_").
Names bound by import statements may not occur in
global statements in the same scope.
The from form with "*" may only occur in a module scope.
(The current implementation does not enforce the latter two
restrictions, but programs should not abuse this freedom, as future
implementations may enforce them or silently change the meaning of the
program.)
Hierarchical module names:
when the module names contains one or more dots, the module search
path is carried out differently. The sequence of identifiers up to
the last dot is used to find a ``package''; the final
identifier is then searched inside the package. A package is
generally a subdirectory of a directory on `sys.path` that has a
file __init__.py.
[XXX Can't be bothered to spell this out right now; see the URL
http://www.python.org/doc/essays/packages.html for more details, also
about how the module search works from inside a package.]
[XXX Also should mention __import__().]