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

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


2. MacPython Modules

node23.html | mac.html | module-mac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2. MacPython Modules
The following modules are only available on the Macintosh, and 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.
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'').
aepack (module-aepack.html) | Conversion between Python variables and AppleEvent
data containers.
aetypes (module-aetypes.html) | Python representation of the Apple Event Object Model.


Module Index

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


3.1 AE -- Apple Events

toolbox.html | toolbox.html | module-Cm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.1 AE -- Apple Events
Availability: Macintosh.


aeserver-objects.html | macpython-modules.html | module-aetypes.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.15 aepack --
Conversion between Python variables and AppleEvent data containers
Availability: Macintosh.
The aepack module defines functions for converting (packing)
Python variables to AppleEvent descriptors and back (unpacking).
Within Python the AppleEvent descriptor is handled by Python objects
of built-in type AEDesc, defined in module AE (module-AE.html).
The aepack module defines the following functions:


2.16 aetypes -- AppleEvent objects

module-aepack.html | macpython-modules.html | toolbox.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.16 aetypes --
AppleEvent objects
Availability: Macintosh.
The aetypes defines classes used to represent Apple Event
object specifiers. An object specifier is essentially an address of an
object implemented in a Apple Event server. An Apple Event specifier
is used as the direct object for an Apple Event or as the argument of
an optional parameter. In AppleScript an object specifier is
represented by a phrase such as:
`character 23 of document "Semprini"`. The classes defined in
this module allow this specifier to be represented by a Python object
which is initialized as follows:
`res = Document(1).Character(23)`
The AEObjects module defines the following class:


undocumented-modules.html | undocumented-modules.html | module-pyresource.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.1 buildtools -- Helper module for BuildApplet and Friends
Availability: Macintosh.


module-pyresource.html | undocumented-modules.html | module-macerrors.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.3 cfmfile -- Code Fragment Resource module
Availability: Macintosh.
cfmfile is a module that understands Code Fragments and the
accompanying ``cfrg'' resources. It can parse them and merge them, and is
used by BuildApplication to combine all plugin modules to a single
executable.


3.2 Cm -- Component Manager

module-AE.html | toolbox.html | module-Ctl.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.2 Cm -- Component Manager
Availability: Cm.


module-macpath.html | macpython-modules.html | connection-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.3 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.


3.3 Ctl -- Control Manager

module-Cm.html | toolbox.html | module-Dlg.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.3 Ctl -- Control Manager
Availability: Macintosh.


3.4 Dlg -- Dialog Manager

module-Ctl.html | toolbox.html | module-Evt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.4 Dlg -- Dialog Manager
Availability: Macintosh.


speech-channel-objects.html | macpython-modules.html | module-FrameWork.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.12 EasyDialogs --
Basic Macintosh dialogs
Availability: Macintosh.
The EasyDialogs module contains some simple dialogs for
the Macintosh. 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:


3.5 Evt -- Event Manager

module-Dlg.html | toolbox.html | module-Fm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.5 Evt -- Event Manager
Availability: Macintosh.


module-macostools.html | macpython-modules.html | module-mactcp.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.9 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:


3.6 Fm -- Font Manager

module-Evt.html | toolbox.html | module-List.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.6 Fm -- Font Manager
Availability: Macintosh.


module-EasyDialogs.html | macpython-modules.html | application-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.13 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 following are some comments posted on the
MacPython newsgroup about the strengths and limitations of
FrameWork:
> The strong point of FrameWork is that it allows you to break
> into the control-flow at many different places. W (module-W.html), for
> instance, uses a different way to enable/disable menus and that plugs
> right in leaving the rest intact. The weak points of
> FrameWork are that it has no abstract command interface (but
> that shouldn't be difficult), that it's dialog support is minimal and
> that it's control/toolbar support is non-existent.
The FrameWork module defines the following functions:


2.6 ic -- Access to Internet Config

finfo-objects.html | macpython-modules.html | node36.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.6 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.). Since MacOS 9, this module is a control panel named Internet.
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:


module-macfsn.html | undocumented-modules.html | module-mactty.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.6 icopen -- Internet Config replacement for open()
Availability: Macintosh.
Importing icopen will replace the builtin open()
with a version that uses Internet Config to set file type and creator
for new files.


3.7 List -- List Manager

module-Fm.html | toolbox.html | module-Menu.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.7 List -- List Manager
Availability: Macintosh.


macpython-modules.html | macpython-modules.html | module-macpath.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.1 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.


connection-object.html | macpython-modules.html | dnr-result-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.4 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:


4.4 macerrors -- MacOS Errors

module-cfmfile.html | undocumented-modules.html | module-macfsn.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.4 macerrors -- MacOS Errors
Availability: Macintosh.
macerrors cotains constant definitions for many MacOS error codes.


dnr-result-object.html | macpython-modules.html | fsspec-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.5 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.
Note: A module, macfsn (module-macfsn.html), is auto-imported to replace
StandardFile calls in macfs with NavServices calls.


4.5 macfsn -- NavServices calls

module-macerrors.html | undocumented-modules.html | module-icopen.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.5 macfsn -- NavServices calls
Availability: Macintosh.
macfsn contains wrapper functions that have the same API as the macfs
StandardFile calls, but are implemented with Navigation Services. Importing it
will replace the methods in macfs with these, if Navigation Services is
available on your machine.


node36.html | macpython-modules.html | module-macostools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.7 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 | macpython-modules.html | module-findertools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.8 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 | macpython-modules.html | module-ctb.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.2 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.


node43.html | macpython-modules.html | voice-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.11 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.


2.10 mactcp -- The MacTCP interfaces

module-findertools.html | macpython-modules.html | node41.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.10 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.


4.7 mactty --

module-icopen.html | undocumented-modules.html | module-nsremote.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.7 mactty --
Availability: Macintosh.


3.8 Menu -- Menu Manager

module-List.html | toolbox.html | module-Qd.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.8 Menu -- Menu Manager
Availability: Macintosh.


dialogwindow-objects.html | macpython-modules.html | aeserver-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 2.14 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. As an
example, it is used in PythonCGISlave.
The MiniAEFrame module defines the following classes:


module-mactty.html | undocumented-modules.html | module-PixMapWrapper.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.8 nsremote -- Wrapper around Netscape OSA modules
Availability: Macintosh.
nsremote is a wrapper around the Netscape OSA modules that
allows you to easily send your browser to a given URL.


module-nsremote.html | undocumented-modules.html | module-preferences.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.9 PixMapWrapper -- Wrapper for PixMap objects
Availability: Macintosh.
PixMapWrapper wraps a PixMap object with a Python object that
allows access to the fields by name. It also has methods to convert
to and from PIL images.


4.10 preferences --

module-PixMapWrapper.html | undocumented-modules.html | module-pythonprefs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.10 preferences --
Availability: Macintosh.


4.2 py_resource --

module-buildtools.html | undocumented-modules.html | module-cfmfile.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.2 py_resource --
Availability: Macintosh.


4.11 pythonprefs --

module-preferences.html | undocumented-modules.html | module-quietconsole.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.11 pythonprefs --
Availability: Macintosh.


3.9 Qd -- QuickDraw

module-Menu.html | toolbox.html | module-Qt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.9 Qd -- QuickDraw
Availability: Macintosh.


3.10 Qt -- QuickTime

module-Qd.html | toolbox.html | module-Res.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.10 Qt -- QuickTime
Availability: Macintosh.


module-pythonprefs.html | undocumented-modules.html | module-W.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.12 quietconsole -- non-visible stdout output
Availability: Macintosh.
quietconsole allows you to keep stdio output in a buffer
without displaying it (or without displaying the stdout window
altogether, if set with EditPythonPrefs) until you try to read from
stdin or disable the buffering, at which point all the saved output is
sent to the window. Good for GUI programs that do want to display their
output at a crash.


module-Qt.html | toolbox.html | module-Scrap.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.11 Res -- Resource Manager and Handles
Availability: Macintosh.


3.12 Scrap -- Scrap Manager

module-Res.html | toolbox.html | module-Snd.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.12 Scrap -- Scrap Manager
Availability: Macintosh.


3.13 Snd -- Sound Manager

module-Scrap.html | toolbox.html | module-TE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.13 Snd -- Sound Manager
Availability: Macintosh.


3.14 TE -- TextEdit

module-Snd.html | toolbox.html | module-waste.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.14 TE -- TextEdit
Availability: Macintosh.


4.13 W -- Widgets built on FrameWork

module-quietconsole.html | undocumented-modules.html | modindex.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4.13 W -- Widgets built on FrameWork
Availability: Macintosh.
The W widgets are used extensively in the IDE.


module-TE.html | toolbox.html | module-Win.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.15 waste -- non-Apple TextEdit replacement
Availability: Macintosh.
See Also:


3.16 Win -- Window Manager

module-waste.html | toolbox.html | undocumented-modules.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3.16 Win -- Window Manager
Availability: Macintosh.


1.5 Creating a Python script

argv.html | using.html | node11.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 1.5 Creating a Python script
Since Python scripts are simply text files, they can be created in any
way that text files can be created, but some special tools also exist
with extra features.


1.5.1 In an editor

node10.html | node10.html | node12.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 1.5.1 In an editor
You can create a text file with any word processing program such as
MSWord or AppleWorks but you need to make sure
that the file is saved as ``ASCII'' or ``plain text''.


1.5.1.1 Editors with Python modes

node11.html | node11.html | scripting-with-BBedit.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
### 1.5.1.1 Editors with Python modes
Several text editors have additional features that add functionality
when you are creating a Python script. These can include coloring
Python keywords to make your code easier to read, module browsing, or
a built-in debugger. These include Alpha, Pepper,
and BBedit, and the MacPython IDE (Section 1.6 (IDE.html#IDE)).


IDE.html | IDE.html | IDEwrite.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 1.6.1 Using the ``Python Interactive'' window
Use this window like you would the PythonInterpreter, except
that you cannot use the ``Drag and drop'' method above. Instead,
dropping a script onto the Python IDE icon will open the
file in a seperate script window (which you can then execute manually
- see section 1.6.3 (IDEexecution.html#IDEexecution)).


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:


1.8 Mac OS X

defaults.html | using.html | macpython-modules.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 1.8 Mac OS X
At the time of this writing Mac OS X had just been released as a
Public Beta. Efforts are under way to bring MacPython to Mac OS X. The
MacPython release 2.01.5.2c1 runs quite well within the
``Classic'' environment. A ``Carbon'' port of the MacPython code is
being prepared for release, and several people have made a command
line version available to the ``Darwin'' layer (which is accessible
via Terminal.app).


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.


2.6.1 IC Objects

module-ic.html | module-ic.html | module-MacOS.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 2.6.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 serve 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:


2.10.1 TCP Stream Objects

module-mactcp.html | module-mactcp.html | node42.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 2.10.1 TCP Stream Objects


2.10.2 TCP Status Objects

node41.html | module-mactcp.html | node43.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 2.10.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:


2.10.3 UDP Stream Objects

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


1.3 How to run a Python script

interpreter.html | using.html | node7.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 1.3 How to run a Python script
There are several ways to run an existing Python script; two common
ways to run a Python script are ``drag and drop'' and ``double
clicking''. Other ways include running it from within the IDE (see
Section 1.6 (IDE.html#IDE)), or launching via AppleScript.


1.3.1 Drag and drop

node6.html | node6.html | creator-code.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 1.3.1 Drag and drop
One of the easiest ways to launch a Python script is via ``Drag and
Drop''. This is just like launching a text file in the Finder by
``dragging'' it over your word processor's icon and ``dropping'' it
there. Make sure that you use an icon referring to the
PythonInterpreter, not the IDE or Idle
icons which have different behaviour which is described below.
Some things that might have gone wrong:
- A window flashes after dropping the script onto the
PythonInterpreter, but then disappears. Most likely this is a
configuration issue; your PythonInterpreter is setup to exit
immediately upon completion, but your script assumes that if it prints
something that text will stick around for a while. To fix this, see
section 1.7.3 (defaults.html#defaults).
- After dropping the script onto the PythonInterpreter, a
window appeared which said: ``File contains `\r` characters
(incorrect line endings?)''. That script probably originated on a
Unix or Windows machine. You will need to change the line endings
to the standard Mac usage. One way to do this is to open the file in
BBedit
(http://www.barebones.com/products/bbedit_lite.html) which can
easily change the line endings between Mac, DOS, and Unix styles.
- When you waved the script icon over the PythonInterpreter,
the PythonInterpreter icon did not hilight. Most likely the
Creator code and document type is unset (or set incorrectly) - this
often happens when a file originates on a non-Mac computer. See
section 1.3.2 (creator-code.html#creator-code) for more details.


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:


1.5.1.2 BBedit

node12.html | node11.html | IDE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
### 1.5.1.2 BBedit
If you use BBEdit to create your scripts you will want to tell it about the Python creator code so that
you can simply double click on the saved file to launch it.
- Launch BBEdit.
- Select ``Preferences'' from the ``Edit'' menu.
- Select ``File Types'' from the scrolling list.
- click on the ``Add...'' button and navigate to
PythonInterpreter in the main directory of the
MacPython distribution; click ``open''.
- Click on the ``Save'' button in the Preferences panel.


2.13.4 ScrolledWindow Object

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


EditPythonPrefs.html | configuration.html | defaults.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 1.7.2 Adding modules to the Module Search Path
When executing an import statement, Python looks for modules
in places defined by the sys.path To edit the
sys.path on a Mac, launch EditPythonPrefs, and
enter them into the largish field at the top (one per line).
Since MacPython defines a main Python directory, the easiest thing is
to add folders to search within the main Python directory. To add a
folder of scripts that you created called ``My Folder'' located in the
main Python Folder, enter "$(PYTHON):My Folder" onto a new line.
To add the Desktop under OS 9 or below, add
"StartupDriveName:Desktop Folder" on a new line.


2.11.2 Speech Channel Objects

voice-objects.html | module-macspeech.html | module-EasyDialogs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 2.11.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.


3. MacOS Toolbox Modules

module-aetypes.html | mac.html | module-AE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 3. MacOS Toolbox Modules
There are a set of modules that provide interfaces to various MacOS
toolboxes. 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 (http://developer.apple.com/techpubs/macos8/mac8.html) or similar works.
Warning! These modules are not yet documented. If you
wish to contribute documentation of any of these modules, please get
in touch with python-docs@python.org.
AE (module-AE.html) | Interface to the Apple Events toolbox
Cm (module-Cm.html) | Interface to the Component Manager
Ctl (module-Ctl.html) | Interface to the Control Manager
Dlg (module-Dlg.html) | Interface to the Dialog Manager
Evt (module-Evt.html) | Interface to the Event Manager
Fm (module-Fm.html) | Interface to the Font Manager
List (module-List.html) | Interface to the List Manager
Menu (module-Menu.html) | Interface to the Menu Manager
Qd (module-Qd.html) | Interface to the QuickDraw toolbox
Qt (module-Qt.html) | Interface to the QuickTime toolbox
Res (module-Res.html) | Interface to the Resource Manager and Handles
Scrap (module-Scrap.html) | Interface to the Scrap Manager
Snd (module-Snd.html) | Interface to the Sound Manager
TE (module-TE.html) | Interface to TextEdit
waste (module-waste.html) | Interface to the ``WorldScript-Aware Styled Text Engine.''
Win (module-Win.html) | Interface to the Window Manager


4. Undocumented Modules

module-Win.html | mac.html | module-buildtools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 4. Undocumented Modules
The modules in this chapter are poorly documented (if at all). If you
wish to contribute documentation of any of these modules, please get in
touch with python-docs@python.org.
buildtools (module-buildtools.html) | Helper module for BuildApple, BuildApplication and macfreeze
py_resource (module-pyresource.html)
cfmfile (module-cfmfile.html) | Code Fragment Resource module
macerrors (module-macerrors.html) | Constant definitions for many MacOS error codes
macfsn (module-macfsn.html) | NavServices versions of StandardFile calls
icopen (module-icopen.html) | Internet Config replacement for open()
mactty (module-mactty.html)
nsremote (module-nsremote.html) | Wrapper around Netscape OSA modules
PixMapWrapper (module-PixMapWrapper.html) | Wrapper for PixMap objects
preferences (module-preferences.html)
pythonprefs (module-pythonprefs.html)
quietconsole (module-quietconsole.html) | buffered, non-visible stdout output
W (module-W.html) | Widgets for the Mac, built on top of FrameWork


1. Using Python on the Macintosh

contents.html | mac.html | getting.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
# 1. Using Python on the Macintosh
Using Python on the Macintosh can seem like something completely
different than using it on a Unix-like or Windows system. Most of the
Python documentation, both the ``official'' documentation and
published books, describe only how Python is used on these systems,
causing confusion for the new user of MacPython. This chapter gives a
brief introduction to the specifics of using Python on a Macintosh.


2.11.1 Voice Objects

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


2.13.2 Window Objects

application-objects.html | module-FrameWork.html | controlswindow-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
---
## 2.13.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,
October 16, 2000, Release 2.0
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 | augassign.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.


6.3.1 Augmented Assignment statements

assignment.html | assignment.html | pass.html | Python Reference Manual | contents.html | genindex.html
---
## 6.3.1 Augmented Assignment statements
Augmented assignment is the combination, in a single statement, of a binary
operation and an assignment statement:
```text

augmented_assignment_stmt: target augop expression_list
augop: "+=" | "-=" | "*=" | "/=" | "%=" | "**="
| ">>=" | "<<=" | "&=" | "^=" | "|="
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 augmented assignment evaluates the target (which, unlike normal
assignment statements, cannot be an unpacking) and the expression
list, performs the binary operation specific to the type of assignment
on the two operands, and assigns the result to the original
target. The target is only evaluated once.
An augmented assignment expression like `x += 1` can be rewritten as
`x = x + 1` to achieve a similar, but not exactly equal effect. In the
augmented version, `x` is only evaluated once. Also, when possible, the
actual operation is performed in-place, meaning that rather than
creating a new object and assigning that to the target, the old object is
modified instead.
With the exception of assigning to tuples and multiple targets in a single
statement, the assignment done by augmented assignment statements is handled
the same way as normal assignments. Similarly, with the exception of the
possible in-place behaviour, the binary operation performed by
augmented assignment is the same as the normal binary operations.


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 (#foot3081) 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 Python
Library Reference (../lib/built-in-funcs.html) 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
Unlike C, all comparison operations in Python have the same priority,
which is lower than that of any arithmetic, shifting or bitwise
operation. Also unlike 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 accepted. The `<>` spelling is considered
obsolescent.
The operators `<`, `>`, `==`, `>=`, `<=`, and
`!=` compare
the values of two objects. The objects need not 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. Unicode and 8-bit strings are fully interoperable in this
behavior.
- 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 (#foot3038)
- 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 set
membership: every type can define membership in whatever way is
appropriate. Traditionally, this interface has been tightly bound
the sequence interface, which is related in that presence in a sequence
can be usefully interpreted as membership in a set.
For the list, tuple types, `x in y` is true if and only
if there exists such an index i such that
`varx == y [ i ]` is true.
For the Unicode and string types, `x in y` is true if
and only if there exists an index i such that `x == y [ i ]` is true. If `x` is not a string or
Unicode object of length `1`, a TypeError exception
is raised.
For user-defined classes which define the __contains__() method,
`x in y` is true if and only if
`y .__contains__( x )` is true.
For user-defined classes which do not define __contains__() and
do define __getitem__(), `x in y` is true if
and only if there is a non-negative integer index i such that
`x == y [ i ]`, and all lower integer indices
do not raise IndexError exception. (If any other exception
is raised, it is as if in raised that exception).
The operator not in is defined to have the inverse true value
of in.
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
Table of Contents
- Front Matter (front.html)
  1. Introduction (introduction.html)
  - 1.1 Notation (notation.html)
  2. Lexical analysis (lexical.html)
  - 2.1 Line structure (line-structure.html)
  - 2.1.1 Logical lines (logical.html)
  2.1.2 Physical lines (physical.html)
  2.1.3 Comments (comments.html)
  2.1.4 Explicit line joining (explicit-joining.html)
  2.1.5 Implicit line joining (implicit-joining.html)
  2.1.6 Blank lines (blank-lines.html)
  2.1.7 Indentation (indentation.html)
  2.1.8 Whitespace between tokens (whitespace.html)
  2.2 Other tokens (other-tokens.html)
  2.3 Identifiers and keywords (identifiers.html)
  - 2.3.1 Keywords (keywords.html)
  2.3.2 Reserved classes of identifiers (id-classes.html)
  2.4 Literals (literals.html)
  - 2.4.1 String literals (strings.html)
  2.4.2 String literal concatenation (string-catenation.html)
  2.4.3 Numeric literals (numbers.html)
  2.4.4 Integer and long integer literals (integers.html)
  2.4.5 Floating point literals (floating.html)
  2.4.6 Imaginary literals (imaginary.html)
  2.5 Operators (operators.html)
  2.6 Delimiters (delimiters.html)
  3. Data model (datamodel.html)
  - 3.1 Objects, values and types (objects.html)
  3.2 The standard type hierarchy (types.html)
  3.3 Special method names (specialnames.html)
  - 3.3.1 Basic customization (customization.html)
  3.3.2 Customizing attribute access (attribute-access.html)
  3.3.3 Emulating callable objects (callable-types.html)
  3.3.4 Emulating sequence and mapping types (sequence-types.html)
  3.3.5 Additional methods for emulation of sequence types (sequence-methods.html)
  3.3.6 Emulating numeric types (numeric-types.html)
  4. Execution model (execmodel.html)
  - 4.1 Code blocks, execution frames, and namespaces (execframes.html)
  4.2 Exceptions (exceptions.html)
  5. Expressions (expressions.html)
  - 5.1 Arithmetic conversions (conversions.html)
  5.2 Atoms (atoms.html)
  - 5.2.1 Identifiers (Names) (atom-identifiers.html)
  5.2.2 Literals (atom-literals.html)
  5.2.3 Parenthesized forms (parenthesized.html)
  5.2.4 List displays (lists.html)
  5.2.5 Dictionary displays (dict.html)
  5.2.6 String conversions (string-conversions.html)
  5.3 Primaries (primaries.html)
  - 5.3.1 Attribute references (attribute-references.html)
  5.3.2 Subscriptions (subscriptions.html)
  5.3.3 Slicings (slicings.html)
  5.3.4 Calls (calls.html)
  5.4 The power operator (power.html)
  5.5 Unary arithmetic operations (unary.html)
  5.6 Binary arithmetic operations (binary.html)
  5.7 Shifting operations (shifting.html)
  5.8 Binary bit-wise operations (bitwise.html)
  5.9 Comparisons (comparisons.html)
  5.10 Boolean operations (lambda.html)
  5.11 Expression lists (exprlists.html)
  5.12 Summary (summary.html)
  6. Simple statements (simple.html)
  - 6.1 Expression statements (exprstmts.html)
  6.2 Assert statements (assert.html)
  6.3 Assignment statements (assignment.html)
  - 6.3.1 Augmented Assignment statements (augassign.html)
  6.4 The pass statement (pass.html)
  6.5 The del statement (del.html)
  6.6 The print statement (print.html)
  6.7 The return statement (return.html)
  6.8 The raise statement (raise.html)
  6.9 The break statement (break.html)
  6.10 The continue statement (continue.html)
  6.11 The import statement (import.html)
  6.12 The global statement (global.html)
  6.13 The exec statement (exec.html)
  7. Compound statements (compound.html)
  - 7.1 The if statement (if.html)
  7.2 The while statement (while.html)
  7.3 The for statement (for.html)
  7.4 The try statement (try.html)
  7.5 Function definitions (function.html)
  7.6 Class definitions (class.html)
  8. Top-level components (top-level.html)
  - 8.1 Complete Python programs (programs.html)
  8.2 File input (file-input.html)
  8.3 Interactive input (interactive.html)
  8.4 Expression input (expression-input.html)
  About this document ... (about.html)
End of Table of 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 (#foot3811)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 second half of the list, the augmented assignment operators, serve
lexically as delimiters, but also perform an operation.
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 (#foot2388)
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 (#foot2396)


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)
```