node100.html | node99.html | modindex.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
A.1 History of the (node100.html)
Up:
A. History and License (node99.html)
Next:
Module Index (modindex.html)
---
# A.2 Terms and conditions for accessing or otherwise using Python
PSF LICENSE AGREEMENT FOR PYTHON 2.3
1. This LICENSE AGREEMENT is between the Python Software Foundation
(``PSF''), and the Individual or Organization (``Licensee'') accessing
and otherwise using Python 2.3 software in source or binary
form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python
2.3 alone or in any derivative version, provided, however, that
PSF's License Agreement and PSF's notice of copyright, i.e.,
``Copyright © 2001-2003 Python Software Foundation; All
Rights Reserved'' are retained in Python 2.3 alone or in any
derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 2.3 or any part thereof, and wants to
make the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 2.3.
4. PSF is making Python 2.3 available to Licensee on an ``AS IS''
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL
NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR
LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON
2.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE
POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python 2.3, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization (``Licensee'') accessing and otherwise
using this software in source or binary form and its associated
documentation (``the Software'').
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an ``AS IS''
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the ``BeOpen Python'' logos available
at http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 (``CNRI''), and the Individual or Organization
(``Licensee'') accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., ``Copyright
© 1995-2001 Corporation for National Research Initiatives;
All Rights Reserved'' are retained in Python 1.6.1 alone or in any
derivative version prepared by Licensee. Alternately, in lieu of
CNRI's License Agreement, Licensee may substitute the following text
(omitting the quotes): ``Python 1.6.1 is made available subject to the
terms and conditions in CNRI's License Agreement. This Agreement
together with Python 1.6.1 may be located on the Internet using the
following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server
on the Internet using the following URL:
http://hdl.handle.net/1895.22/1013.''
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the ``ACCEPT'' button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
Copyright © 1991 - 1995, Stichting Mathematisch Centrum
Amsterdam, The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


1.2.2.1 Drag and drop

node10.html | node10.html | creator-code.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.2.2 How to run (node10.html)
Up:
1.2.2 How to run (node10.html)
Next:
1.2.2.2 Set Creator and (creator-code.html)
---
### 1.2.2.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.2.5 (defaults.html#defaults).
- 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.2.2 (creator-code.html#creator-code) for more details.


1.2.4 Creating a Python script

argv.html | getting.html | node15.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.2.3 Simulating command line (argv.html)
Up:
1.2 Getting and Installing (getting.html)
Next:
1.2.4.1 In an editor (node15.html)
---
## 1.2.4 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.2.4.1 In an editor

node14.html | node14.html | node16.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.2.4 Creating a Python (node14.html)
Up:
1.2.4 Creating a Python (node14.html)
Next:
1.2.4.2 Editors with Python (node16.html)
---
### 1.2.4.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.2.4.2 Editors with Python modes

node15.html | node14.html | scripting-with-BBedit.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.2.4.1 In an editor (node15.html)
Up:
1.2.4 Creating a Python (node14.html)
Next:
1.2.4.3 BBedit (scripting-with-BBedit.html)
---
### 1.2.4.2 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.3 (IDE.html#IDE)).


IDE.html | IDE.html | IDEwrite.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.3 The IDE (IDE.html)
Up:
1.3 The IDE (IDE.html)
Next:
1.3.2 Writing a Python (IDEwrite.html)
---
## 1.3.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 separate script window (which you can then execute manually
- see section 1.3.3 (IDEexecution.html#IDEexecution)).


2.4.1 IC Objects

module-ic.html | module-ic.html | module-MacOS.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
2.4 ic (module-ic.html)
Up:
2.4 ic (module-ic.html)
Next:
2.5 MacOS (module-MacOS.html)
---
## 2.4.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:


1.1.1 How to run a Python script

getting-OSX.html | getting-OSX.html | osx-gui-scripts.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.1 Getting and Installing (getting-OSX.html)
Up:
1.1 Getting and Installing (getting-OSX.html)
Next:
1.1.2 Running scripts with (osx-gui-scripts.html)
---
## 1.1.1 How to run a Python script
Your best way to get started with Python on Mac OS X is through the PythonIDE
integrated development environment, see section 1.3 (IDE.html#IDE) and use the Help
menu when the IDE is running.
If you want to run Python scripts from the Terminal window command line
or from the Finder you first need an editor to create your script.
Mac OS X comes with a number of standard Unix command line editors,
vi and emacs among them. If you want a more Mac-like
editor BBEdit or TextWrangler from Bare Bones Software
(see http://www.barebones.com/products/bbedit/index.shtml) are
good choices. Their freeware BBEdit Lite is officially
discontinued but still available. AppleWorks or any other
word processor that can save files in ASCII is also a possibility, but
TextEdit is not: it saves in .rtf format only.
To run your script from the Terminal window you must make sure that
/usr/local/bin is in your shell search path before /usr/bin,
where the Apple-supplied Python lives (which is version 2.2, as of Mac OS X
10.2.4).
To run your script from the Finder you have two options:
- Drag it to PythonLauncher
- Select PythonLauncher as the default application
to open your script (or any .py script) through the finder Info window
and double-click it.
PythonLauncher has various preferences to control how your script is launched.
Option-dragging allows you to change these for one invocation, or use its
Preferences menu to change things globally.


1.1.3 configuration

osx-gui-scripts.html | getting-OSX.html | getting.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.1.2 Running scripts with (osx-gui-scripts.html)
Up:
1.1 Getting and Installing (getting-OSX.html)
Next:
1.2 Getting and Installing (getting.html)
---
## 1.1.3 configuration
MacPython honours all standard Unix environment variables such as
PYTHONPATH, but setting these variables for programs started
from the Finder is non-standard
as the Finder does not read your .profile or .cshrc at startup.
You need to create a file ~/.MacOSX/environment.plist.
See Apple's Technical Document QA1067 for details.
Installing additional Python packages is most easily done through the
Package Manager, see the MacPython Help Book for details.


A. History and License

module-waste.html | mac.html | node100.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
5.17 waste (module-waste.html)
Up:
Macintosh Library Modules (mac.html)
Next:
A.1 History of the (node100.html)
---
# A. History and License


1.1.2 Running scripts with a GUI

node5.html | getting-OSX.html | node7.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.1.1 How to run (node5.html)
Up:
1.1 Getting and Installing (getting-OSX.html)
Next:
1.1.3 configuration (node7.html)
---
## 1.1.2 Running scripts with a GUI
There is one Mac OS X quirk that you need to be aware of: programs
that talk to the Aqua window manager (in other words, anything that has a GUI)
need to be run in a special way. Use pythonw in stead of python
to start such scripts.


2.8.1 ProgressBar Objects

module-EasyDialogs.html | module-EasyDialogs.html | module-FrameWork.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
2.8 EasyDialogs (module-EasyDialogs.html)
Up:
2.8 EasyDialogs (module-EasyDialogs.html)
Next:
2.9 FrameWork (module-FrameWork.html)
---
## 2.8.1 ProgressBar Objects
ProgressBar objects provide support for modeless progress-bar
dialogs. Both determinate (thermometer style) and indeterminate
(barber-pole style) progress bars are supported. The bar will be
determinate if its maximum value is greater than zero; otherwise it
will be indeterminate.
Changed in version 2.2:
Support for indeterminate-style progress bars was
added.
The dialog is displayed immediately after creation. If the dialog's
``Cancel'' button is pressed, or if Cmd-. or ESC is typed,
the dialog window is hidden and KeyboardInterrupt is
raised (but note that this response does not occur until the progress
bar is next updated, typically via a call to inc() or
set()). Otherwise, the bar remains visible until the
ProgressBar object is discarded.
ProgressBar objects possess the following attributes and
methods:


1.2.4.3 BBedit

node16.html | node14.html | configuration.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
1.2.4.2 Editors with Python (node16.html)
Up:
1.2.4 Creating a Python (node14.html)
Next:
1.2.5 Configuration (configuration.html)
---
### 1.2.4.3 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.


3. MacPython OSA Modules

module-autoGIL.html | mac.html | module-gensuitemodule.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
2.10 autoGIL (module-autoGIL.html)
Up:
Macintosh Library Modules (mac.html)
Next:
3.1 gensuitemodule (module-gensuitemodule.html)
---
# 3. MacPython OSA Modules
Python has a fairly complete implementation of the Open Scripting
Architecure (OSA, also commonly referred to as AppleScript), allowing
you to control scriptable applications from your Python program,
and with a fairly pythonic interface.
For a description of the various components of AppleScript and OSA, and
to get an understanding of the architecture and terminology, you should
read Apple's documentation. The "Applescript Language Guide" explains
the conceptual model and the terminology, and documents the standard
suite. The "Open Scripting Architecture" document explains how to use
OSA from an application programmers point of view. In the Apple Help
Viewer these book sare located in the Developer Documentation, Core
Technologies section.
As an example of scripting an application, the following piece of
AppleScript will get the name of the frontmost Finder window
and print it:
```text

tell application "Finder"
get name of window 1
end tell
```
In Python, the following code fragment will do the same:
```text

import Finder

f = Finder.Finder()
print f.get(f.window(1).name)
```
As distributed the Python library includes packages that implement the
standard suites, plus packages that interface to a small number of
common applications.
To send AppleEvents to an application you must first create the Python
package interfacing to the terminology of the application (what
Script Editor calls the "Dictionary"). This can be done from
within the PythonIDE or by running the
gensuitemodule.py module as a standalone program from the command
line.
The generated output is a package with a number of modules, one for
every suite used in the program plus an __init__ module to glue
it all together. The Python inheritance graph follows the AppleScript
inheritance graph, so if a programs dictionary specifies that it
includes support for the Standard Suite, but extends one or two verbs
with extra arguments then the output suite will contain a module
Standard_Suite that imports and re-exports everything from
StdSuites.Standard_Suite but overrides the methods that have
extra functionality. The output of gensuitemodule is pretty
readable, and contains the documentation that was in the original
AppleScript dictionary in Python docstrings, so reading it is a good
source of documentation.
The output package implements a main class with the same name as the
package which contains all the AppleScript verbs as methods, with the
direct object as the first argument and all optional parameters as
keyword arguments. AppleScript classes are also implemented as Python
classes, as are comparisons and all the other thingies.
The main
Python class implementing the verbs also allows access to the properties
and elements declared in the AppleScript class "application". In the
current release that is as far as the object orientation goes, so
in the example above we need to use
`f.get(f.window(1).name)` in stead of the more Pythonic
`f.window(1).name.get()`.
If an AppleScript identifier is not a Python identifier the name is
mangled according to a small number of rules:
- spaces are replaced with underscores
- other non-alphanumeric characters are replaced with
`_xx_` where `xx` is the hexadecimal character value
- any Python reserved word gets an underscore appended
Python also has support for creating scriptable applications
in Python, but
The following modules are relevant to MacPython AppleScript support:
gensuitemodule (module-gensuitemodule.html) | Create a stub package from an OSA dictionary
aetools (module-aetools.html) | Basic support for sending 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.
MiniAEFrame (module-MiniAEFrame.html) | Support to act as an Open Scripting Architecture (OSA) server
(``Apple Events'').
In addition, support modules have been pre-generated for
Finder, Terminal, Explorer,
Netscape, CodeWarrior, SystemEvents and
StdSuites.


2.9.4 ScrolledWindow Object

controlswindow-object.html | module-FrameWork.html | dialogwindow-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
2.9.3 ControlsWindow Object (controlswindow-object.html)
Up:
2.9 FrameWork (module-FrameWork.html)
Next:
2.9.5 DialogWindow Objects (dialogwindow-objects.html)
---
## 2.9.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
Previous:
1.2.5.1 EditPythonPrefs (EditPythonPrefs.html)
Up:
1.2.5 Configuration (configuration.html)
Next:
1.2.5.3 Default startup options (defaults.html)
---
### 1.2.5.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.


4. MacOS Toolbox Modules

aeserver-objects.html | mac.html | module-Carbon.AE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
3.5.1 AEServer Objects (aeserver-objects.html)
Up:
Macintosh Library Modules (mac.html)
Next:
4.1 Carbon.AE (module-Carbon.AE.html)
---
# 4. 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/documentation/macos8/mac8.html) or similar works.
These modules all live in a package called Carbon. Despite that name
they are not all part of the Carbon framework: CF is really in the CoreFoundation
framework and Qt is in the QuickTime framework.
The normal use pattern is
```text

from Carbon import AE
```
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.
Carbon.AE (module-Carbon.AE.html) | Interface to the Apple Events toolbox.
Carbon.AH (module-Carbon.AH.html) | Interface to the Apple Help manager.
Carbon.App (module-Carbon.App.html) | Interface to the Appearance Manager.
Carbon.CF (module-Carbon.CF.html) | Interface to the Core Foundation.
Carbon.CG (module-Carbon.CG.html) | Interface to the Component Manager.
Carbon.CaronEvt (module-Carbon.CaronEvt.html) | Interface to the Carbon Event Manager.
Carbon.Cm (module-Carbon.Cm.html) | Interface to the Component Manager.
Carbon.Ctl (module-Carbon.Ctl.html) | Interface to the Control Manager.
Carbon.Dlg (module-Carbon.Dlg.html) | Interface to the Dialog Manager.
Carbon.Evt (module-Carbon.Evt.html) | Interface to the classic Event Manager.
Carbon.Fm (module-Carbon.Fm.html) | Interface to the Font Manager.
Carbon.Folder (module-Carbon.Folder.html) | Interface to the Folder Manager.
Carbon.Help (module-Carbon.Help.html) | Interface to the Carbon Help Manager.
Carbon.List (module-Carbon.List.html) | Interface to the List Manager.
Carbon.Menu (module-Carbon.Menu.html) | Interface to the Menu Manager.
Carbon.Mlte (module-Carbon.Mlte.html) | Interface to the MultiLingual Text Editor.
Carbon.Qd (module-Carbon.Qd.html) | Interface to the QuickDraw toolbox.
Carbon.Qdoffs (module-Carbon.Qdoffs.html) | Interface to the QuickDraw Offscreen APIs.
Carbon.Qt (module-Carbon.Qt.html) | Interface to the QuickTime toolbox.
Carbon.Res (module-Carbon.Res.html) | Interface to the Resource Manager and Handles.
Carbon.Scrap (module-Carbon.Scrap.html) | Interface to the Carbon Scrap Manager.
Carbon.Snd (module-Carbon.Snd.html) | Interface to the Sound Manager.
Carbon.TE (module-Carbon.TE.html) | Interface to TextEdit.
Carbon.Win (module-Carbon.Win.html) | Interface to the Window Manager.
ColorPicker (module-ColorPicker.html) | Interface to the standard color selection dialog.


5. Undocumented Modules

module-ColorPicker.html | mac.html | module-applesingle.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
4.25 ColorPicker (module-ColorPicker.html)
Up:
Macintosh Library Modules (mac.html)
Next:
5.1 applesingle (module-applesingle.html)
---
# 5. 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 (mailto:python-docs@python.org).
applesingle (module-applesingle.html) | Rudimentary decoder for AppleSingle format files.
buildtools (module-buildtools.html) | Helper module for BuildApplet, BuildApplication and
macfreeze.
py_resource (module-pyresource.html) | Helper to create 'PYC~' resources for compiled
applications.
cfmfile (module-cfmfile.html) | Code Fragment Resource module.
icopen (module-icopen.html) | Internet Config replacement for open().
macerrors (module-macerrors.html) | Constant definitions for many Mac OS error codes.
macresource (module-macresource.html) | Locate script resources.
Nac (module-Nac.html) | Interface to Navigation Services.
mkcwproject (module-mkcwproject.html) | Create CodeWarrior projects.
nsremote (module-nsremote.html) | Wrapper around Netscape OSA modules.
PixMapWrapper (module-PixMapWrapper.html) | Wrapper for PixMap objects.
preferences (module-preferences.html) | Nice application preferences manager with support for
defaults.
pythonprefs (module-pythonprefs.html) | Specialized preferences manager for the Python
interpreter.
quietconsole (module-quietconsole.html) | Buffered, non-visible standard output.
videoreader (module-videoreader.html) | Read QuickTime movies frame by frame for further processing.
W (module-W.html) | Widgets for the Mac, built on top of FrameWork (module-FrameWork.html).
waste (module-waste.html) | Interface to the ``WorldScript-Aware Styled Text Engine.''


1. Using Python on a Mac OS 9 Macintosh

contents.html | mac.html | getting-OSX.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
Up:
Macintosh Library Modules (mac.html)
Next:
1.1 Getting and Installing (getting-OSX.html)
---
# 1. Using Python on a Mac OS 9 Macintosh
Using Python on a Macintosh, especially on Mac OS 9 (MacPython-OSX
includes a complete Unix Python) 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-OS9. This chapter gives a brief
introduction to the specifics of using Python on a Macintosh.
The section on the IDE (see Section 1.3 (IDE.html#IDE)) is relevant to MacPython-OSX
too.


2.9.2 Window Objects

application-objects.html | module-FrameWork.html | controlswindow-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html
Previous:
2.9.1 Application Objects (application-objects.html)
Up:
2.9 FrameWork (module-FrameWork.html)
Next:
2.9.3 ControlsWindow Object (controlswindow-object.html)
---
## 2.9.2 Window Objects
Window objects have the following methods, among others:


Global Module Index

index.html | 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
Previous:
Up:
Python Reference Manual (ref.html)
---
# About this document ...
Python Reference Manual,
July 29, 2003, Release 2.3
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, either in the content or the presentation, 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.


6.2 Assert statements

exprstmts.html | simple.html | assignment.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.1 Expression statements (exprstmts.html)
Up:
6. Simple statements (simple.html)
Next:
6.3 Assignment statements (assignment.html)
---
# 6.2 Assert statements
Assert statements are a convenient way to insert
debugging assertions into a program:
`assert_stmt` | ::= | `"assert" expression ["," expression ]`
Download entire grammar as text. (grammar.txt)
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.
Assignments to `__debug__` are illegal. The value for the
built-in variable is determined when the interpreter starts.


6.3 Assignment statements

assert.html | simple.html | augassign.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.2 Assert statements (assert.html)
Up:
6. Simple statements (simple.html)
Next:
6.3.1 Augmented assignment statements (augassign.html)
---
# 6.3 Assignment statements
Assignment statements are used to
(re)bind names to values and to modify attributes or items of mutable
objects:
`assignment_stmt` | ::= | `( target_list "=")+ expression_list`
`target_list` | ::= | `target ("," target )* [","]`
`target` | ::= | `identifier`
`| "(" target_list ")"`
`| "[" target_list "]"`
`| attributeref`
`| subscription`
`| slicing`
Download entire grammar as text. (grammar.txt)
(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
Previous:
5.2 Atoms (atoms.html)
Up:
5.2 Atoms (atoms.html)
Next:
5.2.2 Literals (atom-literals.html)
---
## 5.2.1 Identifiers (Names)
An identifier occurring as an atom is a name. See Section 4.1 for
documentation of naming and binding.
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
Previous:
5.2.1 Identifiers (Names) (atom-identifiers.html)
Up:
5.2 Atoms (atoms.html)
Next:
5.2.3 Parenthesized forms (parenthesized.html)
---
## 5.2.2 Literals
Python supports string literals and various numeric literals:
`literal` | ::= | `stringliteral | integer | longinteger`
`| floatnumber | imagnumber`
Download entire grammar as text. (grammar.txt)
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
Previous:
5.1 Arithmetic conversions (conversions.html)
Up:
5. Expressions (expressions.html)
Next:
5.2.1 Identifiers (Names) (atom-identifiers.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:
`atom` | ::= | `identifier | literal | enclosure`
`enclosure` | ::= | `parenth_form | list_display`
`| dict_display | string_conversion`
Download entire grammar as text. (grammar.txt)


3.3.2 Customizing attribute access

customization.html | specialnames.html | new-style-attribute-access.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.1 Basic customization (customization.html)
Up:
3.3 Special method names (specialnames.html)
Next:
3.3.2.1 More attribute access (new-style-attribute-access.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.


5.3.1 Attribute references

primaries.html | primaries.html | subscriptions.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.3 Primaries (primaries.html)
Up:
5.3 Primaries (primaries.html)
Next:
5.3.2 Subscriptions (subscriptions.html)
---
## 5.3.1 Attribute references
An attribute reference is a primary followed by a period and a name:
`attributeref` | ::= | `primary "." identifier`
Download entire grammar as text. (grammar.txt)
The primary must evaluate to an object of a type that supports
attribute references, e.g., a module, list, or an instance. 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
Previous:
6.3 Assignment statements (assignment.html)
Up:
6.3 Assignment statements (assignment.html)
Next:
6.4 The pass statement (pass.html)
---
## 6.3.1 Augmented assignment statements
Augmented assignment is the combination, in a single statement, of a binary
operation and an assignment statement:
`augmented_assignment_stmt` | ::= | `target augop expression_list`
`augop` | ::= | `"+=" | "-=" | "*=" | "/=" | "%=" | "**="`
`| "»=" | "«=" | "&=" | "^=" | "|="`
Download entire grammar as text. (grammar.txt)
(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 behavior, the binary operation performed by
augmented assignment is the same as the normal binary operations.
For targets which are attribute references, the initial value is
retrieved with a getattr() and the result is assigned with a
setattr(). Notice that the two methods do not necessarily
refer to the same variable. When getattr() refers to a class
variable, setattr() still writes to an instance variable.
For example:
```text

class A:
x = 3 # class variable
a = A()
a.x += 1 # writes a.x as 4 leaving A.x as 3
```


5.6 Binary arithmetic operations

unary.html | expressions.html | shifting.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.5 Unary arithmetic operations (unary.html)
Up:
5. Expressions (expressions.html)
Next:
5.7 Shifting operations (shifting.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:
`m_expr` | ::= | `u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr`
`| m_expr "%" u_expr`
`a_expr` | ::= | `m_expr | a_expr "+" m_expr | a_expr "-" m_expr`
Download entire grammar as text. (grammar.txt)
The `*` (multiplication) operator yields the product of its
arguments. The arguments must either both be numbers, or one argument
must be an integer (plain or long) 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) and `//` (floor division) operators yield
the quotient of their 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 absolute
value of the second operand5.1 (#foot4387).
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 numbers; there similar identities hold
approximately where `x/y` is replaced by `floor(x/y)` or
`floor(x/y) - 1`5.2 (#foot4453).
Deprecated since release 2.3.
The floor division operator, the modulo operator,
and the divmod() function are no longer defined for complex
numbers. Instead, convert to a floating point number using the
abs() function if appropriate.
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
Previous:
5.7 Shifting operations (shifting.html)
Up:
5. Expressions (expressions.html)
Next:
5.9 Comparisons (comparisons.html)
---
# 5.8 Binary bit-wise operations
Each of the three bitwise operations has a different priority level:
`and_expr` | ::= | `shift_expr | and_expr "&" shift_expr`
`xor_expr` | ::= | `and_expr | xor_expr "^" and_expr`
`or_expr` | ::= | `xor_expr | or_expr "|" xor_expr`
Download entire grammar as text. (grammar.txt)
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.7 Blank lines

implicit-joining.html | line-structure.html | indentation.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.6 Implicit line joining (implicit-joining.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.8 Indentation (indentation.html)
---
## 2.1.7 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.


5.10 Boolean operations

comparisons.html | expressions.html | lambdas.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.9 Comparisons (comparisons.html)
Up:
5. Expressions (expressions.html)
Next:
5.11 Lambdas (lambdas.html)
---
# 5.10 Boolean operations
Boolean operations have the lowest priority of all Python operations:
`expression` | ::= | `or_test | lambda_form`
`or_test` | ::= | `and_test | or_test "or" and_test`
`and_test` | ::= | `not_test | and_test "and" not_test`
`not_test` | ::= | `comparison | "not" not_test`
`lambda_form` | ::= | `"lambda" [ parameter_list ]: expression`
Download entire grammar as text. (grammar.txt)
In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: `None`, numeric zero of all types, empty sequences
(strings, tuples and lists), and empty mappings (dictionaries). All
other values are interpreted as true.
The operator not yields `1` if its argument is false,
`0` otherwise.
The expression `x and y` first evaluates x; if
x is false, its value is returned; otherwise, y is
evaluated and the resulting value is returned.
The expression `x or y` first evaluates x; if
x is true, its value is returned; otherwise, y is
evaluated and the resulting value is returned.
(Note that neither and nor or restrict the value
and type they return to `0` and `1`, but rather return the
last evaluated argument.
This is sometimes useful, e.g., if `s` is a string that should be
replaced by a default value if it is empty, the expression
`s or 'foo'` yields the desired value. Because not has to
invent a value anyway, it does not bother to return a value of the
same type as its argument, so e.g., `not 'foo'` yields `0`,
not `''`.)


6.10 The break statement

raise.html | simple.html | continue.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.9 The raise statement (raise.html)
Up:
6. Simple statements (simple.html)
Next:
6.11 The continue statement (continue.html)
---
# 6.10 The break statement
`break_stmt` | ::= | `"break"`
Download entire grammar as text. (grammar.txt)
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.4 Emulating callable objects

metaclasses.html | specialnames.html | sequence-types.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.3 Customizing class creation (metaclasses.html)
Up:
3.3 Special method names (specialnames.html)
Next:
3.3.5 Emulating container types (sequence-types.html)
---
## 3.3.4 Emulating callable objects


5.3.4 Calls

slicings.html | primaries.html | power.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.3.3 Slicings (slicings.html)
Up:
5.3 Primaries (primaries.html)
Next:
5.4 The power operator (power.html)
---
## 5.3.4 Calls
A call calls a callable object (e.g., a function) with a possibly empty
series of arguments:
`call` | ::= | `primary "(" [ argument_list [","]] ")"`
`argument_list` | ::= | `positional_arguments ["," keyword_arguments ]`
`["," "*" expression ]`
`["," "**" expression ]`
`| keyword_arguments ["," "*" expression ]`
`["," "**" expression ]`
`| "*" expression ["," "**" expression ]`
`| "**" expression`
`positional_arguments` | ::= | `expression ("," expression )*`
`keyword_arguments` | ::= | `keyword_item ("," keyword_item )*`
`keyword_item` | ::= | `identifier "=" expression`
Download entire grammar as text. (grammar.txt)
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.
If the syntax "*expression" appears in the function call,
"expression" must evaluate to a sequence. Elements from this
sequence are treated as if they were additional positional arguments;
if there are postional arguments x1,...,xN , and
"expression" evaluates to a sequence y1,...,yM, this
is equivalent to a call with M+N positional arguments
x1,...,xN,y1,...,yM.
A consequence of this is that although the "*expression" syntax
appears after any keyword arguments, it is processed
before the keyword arguments (and the
"**expression" argument, if any - see below). So:
```text

>>> def f(a, b):
... print a, b
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
```
It is unusual for both keyword arguments and the
"*expression" syntax to be used in the same call, so in practice
this confusion does not arise.
If the syntax "**expression" appears in the function call,
"expression" must evaluate to a (subclass of) dictionary, the
contents of which are treated as additional keyword arguments. In the
case of a keyword appearing in both "expression" and as an
explicit keyword argument, a TypeError exception is
raised.
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
Previous:
7.5 Function definitions (function.html)
Up:
7. Compound statements (compound.html)
Next:
8. Top-level components (top-level.html)
---
# 7.6 Class definitions
A class definition defines a class object (see section 3.2 (types.html#types)):
`classdef` | ::= | `"class" classname [ inheritance ] ":" suite`
`inheritance` | ::= | `"(" [ expression_list ] ")"`
`classname` | ::= | `identifier`
Download entire grammar as text. (grammar.txt)
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 (naming.html#naming)), 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.


3.3.8 Coercion rules

numeric-types.html | specialnames.html | execmodel.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.7 Emulating numeric types (numeric-types.html)
Up:
3.3 Special method names (specialnames.html)
Next:
4. Execution model (execmodel.html)
---
## 3.3.8 Coercion rules
This section used to document the rules for coercion. As the language
has evolved, the coercion rules have become hard to document
precisely; documenting what one version of one particular
implementation does is undesirable. Instead, here are some informal
guidelines regarding coercion. In Python 3.0, coercion will not be
supported.


2.1.3 Comments

physical.html | line-structure.html | encodings.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.2 Physical lines (physical.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.4 Encoding declarations (encodings.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 | Booleans.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.8 Binary bit-wise operations (bitwise.html)
Up:
5. Expressions (expressions.html)
Next:
5.10 Boolean operations (Booleans.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:
`comparison` | ::= | `or_expr ( comp_operator or_expr )*`
`comp_operator` | ::= | `"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="`
`| "is" ["not"] | ["not"] "in"`
Download entire grammar as text. (grammar.txt)
Comparisons yield boolean values: `True` or `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 converted 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 elements. This means that to compare equal, each
element must compare equal and the two sequences must be of the same
type and have the same length.
If not equal, the sequences are ordered the same as their first
differing elements. For example, `cmp([1,2,x], [1,2,y])` returns
the same as `cmp(x,y)`. If the corresponding element does not
exist, the shorter sequence is ordered first (for example,
`[1,2] < [1,2,3]`).
- Mappings (dictionaries) compare equal if and only if their sorted
(key, value) lists compare equal.5.3 (#foot4090)Outcomes other than equality are resolved consistently, but are not
otherwise defined.5.4 (#foot4400)
- 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. `x in s` evaluates to true if x
is a member of the set s, and false otherwise. `x not in s` returns the negation of `x in s`.
The set membership test has traditionally been bound to sequences; an
object is a member of a set if the set is a sequence and contains an
element equal to that object. However, it is possible for an object
to support membership tests without being a sequence. In particular,
dictionaries support memership testing as a nicer way of spelling
`key in dict`; other mapping types may follow suit.
For the list and tuple types, `x in y` is true if and
only if there exists an index i such that
`x == y [ i ]` is true.
For the Unicode and string types, `x in y` is true if
and only if x is a substring of y. An equivalent test is
`y.find(x) != -1`. Note, x and y need not be the
same type; consequently, `u'ab' in 'abc'` will return `True`.
Empty strings are always considered to be a substring of any other string,
so `"" in "abc"` will return `True`.
Changed in version 2.3:
Previously, x was required to be a string of
length `1`.
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
Previous:
6.14 The exec statement (exec.html)
Up:
Python Reference Manual (ref.html)
Next:
7.1 The if statement (if.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:
`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 )* [";"]`
Download entire grammar as text. (grammar.txt)
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
Previous:
Front Matter (front.html)
Up:
Python Reference Manual (ref.html)
Next:
1. Introduction (introduction.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 Encoding declarations (encodings.html)
  2.1.5 Explicit line joining (explicit-joining.html)
  2.1.6 Implicit line joining (implicit-joining.html)
  2.1.7 Blank lines (blank-lines.html)
  2.1.8 Indentation (indentation.html)
  2.1.9 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 Customizing class creation (metaclasses.html)
  3.3.4 Emulating callable objects (callable-types.html)
  3.3.5 Emulating container types (sequence-types.html)
  3.3.6 Additional methods for emulation of sequence types (sequence-methods.html)
  3.3.7 Emulating numeric types (numeric-types.html)
  3.3.8 Coercion rules (coercion-rules.html)
  4. Execution model (execmodel.html)
  - 4.1 Naming and binding (naming.html)
  - 4.1.1 Interaction with dynamic features (dynamic-features.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 (Booleans.html)
  5.11 Lambdas (lambdas.html)
  5.12 Expression lists (exprlists.html)
  5.13 Evaluation order (evalorder.html)
  5.14 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 yield statement (yield.html)
  6.9 The raise statement (raise.html)
  6.10 The break statement (break.html)
  6.11 The continue statement (continue.html)
  6.12 The import statement (import.html)
  - 6.12.1 Future statements (future.html)
  6.13 The global statement (global.html)
  6.14 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)
  A. History and License (node103.html)
  - A.1 History of the software (node104.html)
  A.2 Terms and conditions for accessing or otherwise using Python (node105.html)
  About this document ... (about.html)
End of Table of Contents


6.11 The continue statement

break.html | simple.html | import.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.10 The break statement (break.html)
Up:
6. Simple statements (simple.html)
Next:
6.12 The import statement (import.html)
---
# 6.11 The continue statement
`continue_stmt` | ::= | `"continue"`
Download entire grammar as text. (grammar.txt)
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 (#foot5622)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
Previous:
5. Expressions (expressions.html)
Up:
5. Expressions (expressions.html)
Next:
5.2 Atoms (atoms.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 (datamodel.html#datamodel). 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
Previous:
3.3 Special method names (specialnames.html)
Up:
3.3 Special method names (specialnames.html)
Next:
3.3.2 Customizing attribute access (attribute-access.html)
---
## 3.3.1 Basic customization


3. Data model

delimiters.html | ref.html | objects.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.6 Delimiters (delimiters.html)
Up:
Python Reference Manual (ref.html)
Next:
3.1 Objects, values and (objects.html)
---
# 3. Data model


6.5 The del statement

pass.html | simple.html | print.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.4 The pass statement (pass.html)
Up:
6. Simple statements (simple.html)
Next:
6.6 The print statement (print.html)
---
# 6.5 The del statement
`del_stmt` | ::= | `"del" target_list`
Download entire grammar as text. (grammar.txt)
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
from the local or global namespace, depending on whether the name
occurs in a global statement in the same code block. If the
name is unbound, a NameError exception will be raised.
It is illegal to delete a name from the local namespace if it occurs
as a free variable in a nested 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
Previous:
2.5 Operators (operators.html)
Up:
2. Lexical analysis (lexical.html)
Next:
3. Data model (datamodel.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:


3.3.2.3 Invoking Descriptors

descriptors.html | attribute-access.html | slots.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.2.2 Implementing Descriptors (descriptors.html)
Up:
3.3.2 Customizing attribute access (attribute-access.html)
Next:
3.3.2.4 __slots__ (slots.html)
---
### 3.3.2.3 Invoking Descriptors
In general, a descriptor is an object attribute with ``binding behavior'',
one whose attribute access has been overridden by methods in the descriptor
protocol: __get__(), __set__(), and __delete__().
If any of those methods are defined for an object, it is said to be a
descriptor.
The default behavior for attribute access is to get, set, or delete the
attribute from an object's dictionary. For instance, `a.x` has a
lookup chain starting with `a.__dict__['x']`, then
`type(a).__dict__['x']`, and continuing
through the base classes of `type(a)` excluding metaclasses.
However, if the looked-up value is an object defining one of the descriptor
methods, then Python may override the default behavior and invoke the
descriptor method instead. Where this occurs in the precedence chain depends
on which descriptor methods were defined and how they were called. Note that
descriptors are only invoked for new style objects or classes
(ones that subclass object() or type()).
The starting point for descriptor invocation is a binding, `a.x`.
How the arguments are assembled depends on `a`:
Direct Call: The simplest and least common call is when user code
directly invokes a descriptor method: `x.__get__(a)`.
Instance Binding: If binding to a new-style object instance,
`a.x` is transformed into the call:
`type(a).__dict__['x'].__get__(a, type(a))`.
Class Binding: If binding to a new-style class, `A.x`
is transformed into the call: `A.__dict__['x'].__get__(None, A)`.
Super Binding: If `a` is an instance of super,
then the binding `super(B, obj).m()` searches
`obj.__class__.__mro__` for the base class `A` immediately
preceding `B` and then invokes the descriptor with the call:
`A.__dict__['m'].__get__(obj, A)`.
For instance bindings, the precedence of descriptor invocation depends
on the which descriptor methods are defined. Data descriptors define
both __get__() and __set__(). Non-data descriptors have
just the __get__() method. Data descriptors always override
a redefinition in an instance dictionary. In contrast, non-data
descriptors can be overridden by instances.
Python methods (including staticmethod() and classmethod())
are implemented as non-data descriptors. Accordingly, instances can
redefine and override methods. This allows individual instances to acquire
behaviors that differ from other instances of the same class.
The property() function is implemented as a data descriptor.
Accordingly, instances cannot override the behavior of a property.


3.3.2.2 Implementing Descriptors

new-style-attribute-access.html | attribute-access.html | descriptor-invocation.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.2.1 More attribute access (new-style-attribute-access.html)
Up:
3.3.2 Customizing attribute access (attribute-access.html)
Next:
3.3.2.3 Invoking Descriptors (descriptor-invocation.html)
---
### 3.3.2.2 Implementing Descriptors
The following methods only apply when an instance of the class
containing the method (a so-called descriptor class) appears in
the class dictionary of another new-style class, known as the
owner class. In the examples below, ``the attribute'' refers to
the attribute whose name is the key of the property in the owner
class' `__dict__`.


5.2.5 Dictionary displays

lists.html | atoms.html | string-conversions.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.2.4 List displays (lists.html)
Up:
5.2 Atoms (atoms.html)
Next:
5.2.6 String conversions (string-conversions.html)
---
## 5.2.5 Dictionary displays
A dictionary display is a possibly empty series of key/datum pairs
enclosed in curly braces:
`dict_display` | ::= | `"{" [ key_datum_list ] "}"`
`key_datum_list` | ::= | `key_datum ("," key_datum )* [","]`
`key_datum` | ::= | `expression ":" expression`
Download entire grammar as text. (grammar.txt)
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.1.1 Interaction with dynamic features

naming.html | naming.html | exceptions.html | Python Reference Manual | contents.html | genindex.html
Previous:
4.1 Naming and binding (naming.html)
Up:
4.1 Naming and binding (naming.html)
Next:
4.2 Exceptions (exceptions.html)
---
## 4.1.1 Interaction with dynamic features
There are several cases where Python statements are illegal when
used in conjunction with nested scopes that contain free
variables.
If a variable is referenced in an enclosing scope, it is illegal
to delete the name. An error will be reported at compile time.
If the wild card form of import -- "import *" -- is used in a
function and the function contains or is a nested block with free
variables, the compiler will raise a SyntaxError.
If exec is used in a function and the function contains or
is a nested block with free variables, the compiler will raise a
SyntaxError unless the exec explicitly specifies the local
namespace for the exec. (In other words, "exec obj"would be illegal, but "exec obj in ns" would be legal.)
The eval(), execfile(), and input()
functions and the exec statement do not have access to the
full environment for resolving names. Names may be resolved in the
local and global namespaces of the caller. Free variables are not
resolved in the nearest enclosing namespace, but in the global
namespace.4.1 (#foot3394)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.


2.1.4 Encoding declarations

comments.html | line-structure.html | explicit-joining.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.3 Comments (comments.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.5 Explicit line joining (explicit-joining.html)
---
## 2.1.4 Encoding declarations
If a comment in the first or second line of the Python script matches
the regular expression coding[=:]\s*([\w-_.]+), this comment is
processed as an encoding declaration; the first group of this
expression names the encoding of the source code file. The recommended
forms of this expression are
```text

# -*- coding: <encoding-name> -*-
```
which is recognized also by GNU Emacs, and
```text

# vim:fileencoding=<encoding-name>
```
which is recognized by Bram Moolenar's VIM. In addition, if the first
bytes of the file are the UTF-8 byte-order mark
(`'\xef\xbb\xbf'`), the declared file encoding is UTF-8
(this is supported, among others, by Microsoft's notepad).
If an encoding is declared, the encoding name must be recognized by
Python. The encoding is used for all lexical analysis, in particular to find
the end of a string, and to interpret the contents of Unicode literals.
String literals are converted to Unicode for syntactical analysis,
then converted back to their original encoding before interpretation
starts. The encoding declaration must appear on a line of its own.


5.13 Evaluation order

exprlists.html | expressions.html | summary.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.12 Expression lists (exprlists.html)
Up:
5. Expressions (expressions.html)
Next:
5.14 Summary (summary.html)
---
# 5.13 Evaluation order
Python evaluates expressions from left to right. Notice that while
evaluating an assignment, the right-hand side is evaluated before
the left-hand side.
In the following lines, expressions will be evaluated in the
arithmetic order of their suffixes:
```text

expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
func(expr1, expr2, *expr3, **expr4)
expr3, expr4 = expr1, expr2
```


4.2 Exceptions

dynamic-features.html | execmodel.html | expressions.html | Python Reference Manual | contents.html | genindex.html
Previous:
4.1.1 Interaction with dynamic (dynamic-features.html)
Up:
4. Execution model (execmodel.html)
Next:
5. Expressions (expressions.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
raisedat the point where the error
is detected; it may be handledby
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 class instances.
Selection of a matching except clause is based on object identity.
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 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.
Warning:
Messages to exceptions are not part of the Python API. Their contents may
change from one version of Python to the next without warning and should not
be relied on by code which will run under multiple versions of the
interpreter.


6.14 The exec statement

global.html | simple.html | compound.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.13 The global statement (global.html)
Up:
6. Simple statements (simple.html)
Next:
7. Compound statements (compound.html)
---
# 6.14 The exec statement
`exec_stmt` | ::= | `"exec" expression ["in" expression ["," expression ]]`
Download entire grammar as text. (grammar.txt)
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.


4. Execution model

coercion-rules.html | ref.html | naming.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.8 Coercion rules (coercion-rules.html)
Up:
Python Reference Manual (ref.html)
Next:
4.1 Naming and binding (naming.html)
---
# 4. Execution model


2.1.5 Explicit line joining

encodings.html | line-structure.html | implicit-joining.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.4 Encoding declarations (encodings.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.6 Implicit line joining (implicit-joining.html)
---
## 2.1.5 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 | node103.html | Python Reference Manual | contents.html | genindex.html
Previous:
8.3 Interactive input (interactive.html)
Up:
8. Top-level components (top-level.html)
Next:
A. History and License (node103.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:
`eval_input` | ::= | `expression_list NEWLINE*`
Download entire grammar as text. (grammar.txt)
The input line read by input() must have the following form:
`input_input` | ::= | `expression_list NEWLINE`
Download entire grammar as text. (grammar.txt)
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
Previous:
4.2 Exceptions (exceptions.html)
Up:
Python Reference Manual (ref.html)
Next:
5.1 Arithmetic conversions (conversions.html)
---
# 5. Expressions
This chapter explains the meaning of the elements of expressions in
Python.
Syntax Notes: In this and the following chapters, extended
BNFnotation will be used to describe syntax, not lexical
analysis. When (one alternative of) a syntax rule has the form
`name` | ::= | `othername`
and no semantics are given, the semantics of this form of `name`
are the same as for `othername`.


5.12 Expression lists

lambdas.html | expressions.html | evalorder.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.11 Lambdas (lambdas.html)
Up:
5. Expressions (expressions.html)
Next:
5.13 Evaluation order (evalorder.html)
---
# 5.12 Expression lists
`expression_list` | ::= | `expression ( "," expression )* [","]`
Download entire grammar as text. (grammar.txt)
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
Previous:
6. Simple statements (simple.html)
Up:
6. Simple statements (simple.html)
Next:
6.2 Assert statements (assert.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:
`expression_stmt` | ::= | `expression_list`
Download entire grammar as text. (grammar.txt)
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
Previous:
8.1 Complete Python programs (programs.html)
Up:
8. Top-level components (top-level.html)
Next:
8.3 Interactive input (interactive.html)
---
# 8.2 File input
All input read from non-interactive files has the same form:
`file_input` | ::= | `(NEWLINE | statement )*`
Download entire grammar as text. (grammar.txt)
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;