2.4.5 Floating point literals

integers.html | literals.html | imaginary.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.4.4 Integer and long (integers.html)
Up:
2.4 Literals (literals.html)
Next:
2.4.6 Imaginary literals (imaginary.html)
---
## 2.4.5 Floating point literals
Floating point literals are described by the following lexical
definitions:
`floatnumber` | ::= | `pointfloat | exponentfloat`
`pointfloat` | ::= | `[ intpart ] fraction | intpart "."`
`exponentfloat` | ::= | `( intpart | pointfloat ) exponent`
`intpart` | ::= | `digit +`
`fraction` | ::= | `"." digit +`
`exponent` | ::= | `("e" | "E") ["+" | "-"] digit +`
Download entire grammar as text. (grammar.txt)
Note that the integer and exponent parts of floating point numbers
can look like octal integers, but are interpreted using radix 10. For
example, "077e010" is legal, and denotes the same number
as "77e10".
The allowed range of floating point literals is
implementation-dependent.
Some examples of floating point literals:
```text

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


7.3 The for statement

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

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


Front Matter

ref.html | ref.html | contents.html | Python Reference Manual | contents.html | genindex.html
Previous:
Python Reference Manual (ref.html)
Up:
Python Reference Manual (ref.html)
Next:
---
# Front Matter
Copyright © 2001, 2002, 2003 Python Software Foundation.
All rights reserved.
Copyright © 2000 BeOpen.com.
All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives.
All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum.
All rights reserved.
See the end of this document for complete license and permissions
information.
### Abstract:
Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics. Its high-level built in data
structures, combined with dynamic typing and dynamic binding, make it
very attractive for rapid application development, as well as for use
as a scripting or glue language to connect existing components
together. Python's simple, easy to learn syntax emphasizes
readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages
program modularity and code reuse. The Python interpreter and the
extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
This reference manual describes the syntax and ``core semantics'' of
the language. It is terse, but attempts to be exact and complete.
The semantics of non-essential built-in object types and of the
built-in functions and modules are described in the
Python Library Reference (../lib/lib.html). For an
informal introduction to the language, see the
Python Tutorial (../tut/tut.html). For C or
C++ programmers, two additional manuals exist:
Extending and Embedding the Python
Interpreter (../ext/ext.html) describes the high-level picture of how to write a Python
extension module, and the Python/C API
Reference Manual (../api/api.html) describes the interfaces available to
C/C++ programmers in detail.


7.5 Function definitions

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

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

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

Programmer's note: Functions are first-class objects. A
```def`'' form executed inside a function definition defines a
local function that can be returned or passed around. Free variables
used in the nested function can access the local variables of the
function containing the def. See section 4.1 (naming.html#naming) for details.


6.12.1 Future statements

import.html | import.html | global.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.12 The import statement (import.html)
Up:
6.12 The import statement (import.html)
Next:
6.13 The global statement (global.html)
---
## 6.12.1 Future statements
A future statement is a directive to
the compiler that a particular module should be compiled using syntax
or semantics that will be available in a specified future release of
Python. The future statement is intended to ease migration to future
versions of Python that introduce incompatible changes to the
language. It allows use of the new features on a per-module basis
before the release in which the feature becomes standard.
`future_statement` | ::= | `"from" "__future__" "import" feature ["as" name]`
`("," feature ["as" name])*`
`feature` | ::= | `identifier`
`name` | ::= | `identifier`
A future statement must appear near the top of the module. The only
lines that can appear before a future statement are:
- the module docstring (if any),
- comments,
- blank lines, and
- other future statements.
The features recognized by Python 2.3 are "generators",
"division" and "nested_scopes". "generators" and
"nested_scopes" are redundant in 2.3 because they are always
enabled.
A future statement is recognized and treated specially at compile
time: Changes to the semantics of core constructs are often
implemented by generating different code. It may even be the case
that a new feature introduces new incompatible syntax (such as a new
reserved word), in which case the compiler may need to parse the
module differently. Such decisions cannot be pushed off until
runtime.
For any given release, the compiler knows which feature names have been
defined, and raises a compile-time error if a future statement contains
a feature not known to it.
The direct runtime semantics are the same as for any import statement:
there is a standard module __future__, described later, and
it will be imported in the usual way at the time the future statement
is executed.
The interesting runtime semantics depend on the specific feature
enabled by the future statement.
Note that there is nothing special about the statement:
```text

import __future__ [as name]
```
That is not a future statement; it's an ordinary import statement with
no special semantics or syntax restrictions.
Code compiled by an exec statement or calls to the builtin functions
compile() and execfile() that occur in a module
M containing a future statement will, by default, use the new
syntax or semantics associated with the future statement. This can,
starting with Python 2.2 be controlled by optional arguments to
compile() -- see the documentation of that function in the
library reference for details.
A future statement typed at an interactive interpreter prompt will
take effect for the rest of the interpreter session. If an
interpreter is started with the -i option, is passed a
script name to execute, and the script includes a future statement, it
will be in effect in the interactive session started after the script
is executed.


Index

node105.html | ref.html | about.html | Python Reference Manual | contents.html
Previous:
A.2 Terms and conditions (node105.html)
Up:
Python Reference Manual (ref.html)
Next:
About this document ... (about.html)
---
## Index
---
Symbols (#letter-Symbols) |
_ (#letter-_) |
a (#letter-a) |
b (#letter-b) |
c (#letter-c) |
d (#letter-d) |
e (#letter-e) |
f (#letter-f) |
g (#letter-g) |
h (#letter-h) |
i (#letter-i) |
j (#letter-j) |
k (#letter-k) |
l (#letter-l) |
m (#letter-m) |
n (#letter-n) |
o (#letter-o) |
p (#letter-p) |
q (#letter-q) |
r (#letter-r) |
s (#letter-s) |
t (#letter-t) |
u (#letter-u) |
v (#letter-v) |
w (#letter-w) |
x (#letter-x) |
y (#letter-y) |
z (#letter-z)
---
## Symbols
---
## _ (underscore)
---
## A
---
## B
---
## C
---
## D
---
## E
---
## F
---
## G
---
## H
---
## I
---
## J
---
## K
---
## L
---
## M
---
## N
---
## O
---
## P
---
## Q
---
## R
---
## S
---
## T
---
## U
---
## V
---
## W
---
## X
---
## Y
---
## Z


6.13 The global statement

future.html | simple.html | exec.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.12.1 Future statements (future.html)
Up:
6. Simple statements (simple.html)
Next:
6.14 The exec statement (exec.html)
---
# 6.13 The global statement
`global_stmt` | ::= | `"global" identifier ("," identifier )*`
Download entire grammar as text. (grammar.txt)
The global statement is a declaration which holds for the
entire current code block. It means that the listed identifiers are to be
interpreted as globals. It would be impossible to assign to a global
variable without global, although free variables may refer
to globals without being declared global.
Names listed in a global statement must not be used in the same
code block textually preceding that global statement.
Names listed in a global statement must not be defined as formal
parameters or in a for loop control target, class
definition, function definition, or import statement.
(The current implementation does not enforce the latter two
restrictions, but programs should not abuse this freedom, as future
implementations may enforce them or silently change the meaning of the
program.)
Programmer's note:
the global is a directive to the parser. It
applies only to code parsed at the same time as the global
statement. In particular, a global statement contained in an
exec statement does not affect the code block containing
the exec statement, and code contained in an exec
statement is unaffected by global statements in the code
containing the exec statement. The same applies to the
eval(), execfile() and compile() functions.


2.3.2 Reserved classes of identifiers

keywords.html | identifiers.html | literals.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.3.1 Keywords (keywords.html)
Up:
2.3 Identifiers and keywords (identifiers.html)
Next:
2.4 Literals (literals.html)
---
## 2.3.2 Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special
meanings. These are:
See sections: 6.12 (import.html#import), ``The import statement'';
3.3 (specialnames.html#specialnames), ``Special method names'';
5.2.1 (atom-identifiers.html#atom-identifiers), ``Identifiers (Names)''.
Note:
(1): The special identifier "_" is used in the interactive
interpreter to store the result of the last evaluation; it is stored
in the __builtin__ module. When not in interactive mode,
"_" has no special meaning and is not defined.


2.3 Identifiers and keywords

other-tokens.html | lexical.html | keywords.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.2 Other tokens (other-tokens.html)
Up:
2. Lexical analysis (lexical.html)
Next:
2.3.1 Keywords (keywords.html)
---
# 2.3 Identifiers and keywords
Identifiers (also referred to as names) are described by the following
lexical definitions:
`identifier` | ::= | `( letter |"_") ( letter | digit | "_")*`
`letter` | ::= | `lowercase | uppercase`
`lowercase` | ::= | `"a"..."z"`
`uppercase` | ::= | `"A"..."Z"`
`digit` | ::= | `"0"..."9"`
Download entire grammar as text. (grammar.txt)
Identifiers are unlimited in length. Case is significant.


7.1 The if statement

compound.html | compound.html | while.html | Python Reference Manual | contents.html | genindex.html
Previous:
7. Compound statements (compound.html)
Up:
7. Compound statements (compound.html)
Next:
7.2 The while statement (while.html)
---
# 7.1 The if statement
The if statement is used for conditional execution:
`if_stmt` | ::= | `"if" expression ":" suite`
`( "elif" expression ":" suite )*`
`["else" ":" suite ]`
Download entire grammar as text. (grammar.txt)
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section 5.10 (Booleans.html#Booleans) for
the definition of true and false); then that suite is executed (and no
other part of the if statement is executed or evaluated). If
all expressions are false, the suite of the else clause, if
present, is executed.


2.4.6 Imaginary literals

floating.html | literals.html | operators.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.4.5 Floating point literals (floating.html)
Up:
2.4 Literals (literals.html)
Next:
2.5 Operators (operators.html)
---
## 2.4.6 Imaginary literals
Imaginary literals are described by the following lexical definitions:
`imagnumber` | ::= | `( floatnumber | intpart ) ("j" | "J")`
Download entire grammar as text. (grammar.txt)
An imaginary literal yields a complex number with a real part of
0.0. Complex numbers are represented as a pair of floating point
numbers and have the same restrictions on their range. To create a
complex number with a nonzero real part, add a floating point number
to it, e.g., `(3+4j)`. Some examples of imaginary literals:
```text

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


2.1.6 Implicit line joining

explicit-joining.html | line-structure.html | blank-lines.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.5 Explicit line joining (explicit-joining.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.7 Blank lines (blank-lines.html)
---
## 2.1.6 Implicit line joining
Expressions in parentheses, square brackets or curly braces can be
split over more than one physical line without using backslashes.
For example:
```text

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


6.12 The import statement

continue.html | simple.html | future.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.11 The continue statement (continue.html)
Up:
6. Simple statements (simple.html)
Next:
6.12.1 Future statements (future.html)
---
# 6.12 The import statement
`import_stmt` | ::= | `"import" module ["as" name ]
( "," module ["as" name ] )*`
`| "from" module "import" identifier ["as" name ]`
`( "," identifier ["as" name ] )*`
`| "from" module "import" "*"`
`module` | ::= | `( identifier ".")* identifier`
Download entire grammar as text. (grammar.txt)
Import statements are executed in two steps: (1) find a module, and
initialize it if necessary; (2) define a name or names in the local
namespace (of the scope where the import statement occurs).
The first form (without from) repeats these steps for each
identifier in the list. The form with from performs step
(1) once, and then performs step (2) repeatedly.
In this context, to ``initialize'' a built-in or extension module means to
call an initialization function that the module must provide for the purpose
(in the reference implementation, the function's name is obtained by
prepending string ``init'' to the module's name); to ``initialize'' a
Python-coded module means to execute the module's body.
The system maintains a table of modules that have been or are being
initialized,
indexed by module name. This table is
accessible as `sys.modules`. When a module name is found in
this table, step (1) is finished. If not, a search for a module
definition is started. When a module is found, it is loaded. Details
of the module searching and loading process are implementation and
platform specific. It generally involves searching for a ``built-in''
module with the given name and then searching a list of locations
given as `sys.path`.
If a built-in module is found, its
built-in initialization code is executed and step (1) is finished. If
no matching file is found,
ImportError is raised.
If a file is found, it is parsed,
yielding an executable code block. If a syntax error occurs,
SyntaxError is raised. Otherwise, an
empty module of the given name is created and inserted in the module
table, and then the code block is executed in the context of this
module. Exceptions during this execution terminate step (1).
When step (1) finishes without raising an exception, step (2) can
begin.
The first form of import statement binds the module name in
the local namespace to the module object, and then goes on to import
the next identifier, if any. If the module name is followed by
as, the name following as is used as the local
name for the module.
The from form does not bind the module name: it goes through the
list of identifiers, looks each one of them up in the module found in step
(1), and binds the name in the local namespace to the object thus found.
As with the first form of import, an alternate local name can be
supplied by specifying "as localname". If a name is not found,
ImportError is raised. If the list of identifiers is replaced
by a star ("*"), all public names defined in the module are
bound in the local namespace of the import statement..
The public names defined by a module are determined by checking
the module's namespace for a variable named `__all__`; if
defined, it must be a sequence of strings which are names defined or
imported by that module. The names given in `__all__` are all
considered public and are required to exist. If `__all__` is not
defined, the set of public names includes all names found in the
module's namespace which do not begin with an underscore character
("_"). `__all__` should contain the entire public API.
It is intended to avoid accidentally exporting items that are not part
of the API (such as library modules which were imported and used within
the module).
The from form with "*" may only occur in a module
scope. 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.
Hierarchical module names:when the module names contains one or more dots, the module search
path is carried out differently. The sequence of identifiers up to
the last dot is used to find a ``package''; the final
identifier is then searched inside the package. A package is
generally a subdirectory of a directory on `sys.path` that has a
file __init__.py.[XXX Can't be bothered to spell this out right now; see the URL
http://www.python.org/doc/essays/packages.html for more details, also
about how the module search works from inside a package.]
The built-in function __import__() is provided to support
applications that determine which modules need to be loaded
dynamically; refer to Built-in
Functions (../lib/built-in-funcs.html) in the
Python Library Reference (../lib/lib.html) for additional
information.


2.1.8 Indentation

blank-lines.html | line-structure.html | whitespace.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.7 Blank lines (blank-lines.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.9 Whitespace between tokens (whitespace.html)
---
## 2.1.8 Indentation
Leading whitespace (spaces and tabs) at the beginning of a logical
line is used to compute the indentation level of the line, which in
turn is used to determine the grouping of statements.
First, tabs are replaced (from left to right) by one to eight spaces
such that the total number of characters up to and including the
replacement is a multiple of
eight (this is intended to be the same rule as used by Unix). The
total number of spaces preceding the first non-blank character then
determines the line's indentation. Indentation cannot be split over
multiple physical lines using backslashes; the whitespace up to the
first backslash determines the indentation.
Cross-platform compatibility note: because of the nature of
text editors on non-UNIX platforms, it is unwise to use a mixture of
spaces and tabs for the indentation in a single source file. It
should also be noted that different platforms may explicitly limit the
maximum indentation level.
A formfeed character may be present at the start of the line; it will
be ignored for the indentation calculations above. Formfeed
characters occurring elsewhere in the leading whitespace have an
undefined effect (for instance, they may reset the space count to
zero).
The indentation levels of consecutive lines are used to generate
INDENT and DEDENT tokens, using a stack, as follows.
Before the first line of the file is read, a single zero is pushed on
the stack; this will never be popped off again. The numbers pushed on
the stack will always be strictly increasing from bottom to top. At
the beginning of each logical line, the line's indentation level is
compared to the top of the stack. If it is equal, nothing happens.
If it is larger, it is pushed on the stack, and one INDENT token is
generated. If it is smaller, it must be one of the numbers
occurring on the stack; all numbers on the stack that are larger are
popped off, and for each number popped off a DEDENT token is
generated. At the end of the file, a DEDENT token is generated for
each number remaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece
of Python code:
```text

def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
```
The following example shows various indentation errors:
```text

def perm(l): # error: first line indented
for i in range(len(l)): # error: not indented
s = l[:i] + l[i+1:]
p = perm(l[:i] + l[i+1:]) # error: unexpected indent
for x in p:
r.append(l[i:i+1] + x)
return r # error: inconsistent dedent
```
(Actually, the first three errors are detected by the parser; only the
last error is found by the lexical analyzer -- the indentation of
`return r` does not match a level popped off the stack.)


Python Reference Manual

../index.html | front.html | Python Reference Manual | contents.html | genindex.html
Up:
Python Documentation Index (../index.html)
Next:
Front Matter (front.html)
---
# Python Reference Manual
Guido van Rossum
Fred L. Drake, Jr., editor
PythonLabs
Email: python-docs@python.org
Release 2.3
July 29, 2003


2.4.4 Integer and long integer literals

numbers.html | literals.html | floating.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.4.3 Numeric literals (numbers.html)
Up:
2.4 Literals (literals.html)
Next:
2.4.5 Floating point literals (floating.html)
---
## 2.4.4 Integer and long integer literals
Integer and long integer literals are described by the following
lexical definitions:
`longinteger` | ::= | `integer ("l" | "L")`
`integer` | ::= | `decimalinteger | octinteger | hexinteger`
`decimalinteger` | ::= | `nonzerodigit digit * | "0"`
`octinteger` | ::= | `"0" octdigit +`
`hexinteger` | ::= | `"0" ("x" | "X") hexdigit +`
`nonzerodigit` | ::= | `"1"..."9"`
`octdigit` | ::= | `"0"..."7"`
`hexdigit` | ::= | `digit | "a"..."f" | "A"..."F"`
Download entire grammar as text. (grammar.txt)
Although both lower case "l" and upper case "L" are
allowed as suffix for long integers, it is strongly recommended to always
use "L", since the letter "l" looks too much like the
digit "1".
Plain integer decimal literals that are above the largest representable
plain integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted
as if they were long integers instead. Octal and hexadecimal literals
behave similarly, but when in the range just above the largest representable
plain integer but below the largest unsigned 32-bit number (on a machine
using 32-bit arithmetic), 4294967296, they are taken as the negative plain
integer obtained by subtracting 4294967296 from their unsigned value. There
is no limit for long integer literals apart from what can be stored in
available memory. For example, 0xdeadbeef is taken, on a 32-bit machine,
as the value -559038737, while 0xdeadbeeffeed is taken as the value
244837814107885L.
Some examples of plain integer literals (first row) and long integer
literals (second and third rows):
```text

7 2147483647 0177 0x80000000
3L 79228162514264337593543950336L 0377L 0x100000000L
79228162514264337593543950336 0xdeadbeeffeed
```


8.3 Interactive input

file-input.html | top-level.html | expression-input.html | Python Reference Manual | contents.html | genindex.html
Previous:
8.2 File input (file-input.html)
Up:
8. Top-level components (top-level.html)
Next:
8.4 Expression input (expression-input.html)
---
# 8.3 Interactive input
Input in interactive mode is parsed using the following grammar:
`interactive_input` | ::= | `[ stmt_list ] NEWLINE | compound_stmt NEWLINE`
Download entire grammar as text. (grammar.txt)
Note that a (top-level) compound statement must be followed by a blank
line in interactive mode; this is needed to help the parser detect the
end of the input.


1. Introduction

contents.html | ref.html | notation.html | Python Reference Manual | contents.html | genindex.html
Previous:
Up:
Python Reference Manual (ref.html)
Next:
1.1 Notation (notation.html)
---
# 1. Introduction
This reference manual describes the Python programming language.
It is not intended as a tutorial.
While I am trying to be as precise as possible, I chose to use English
rather than formal specifications for everything except syntax and
lexical analysis. This should make the document more understandable
to the average reader, but will leave room for ambiguities.
Consequently, if you were coming from Mars and tried to re-implement
Python from this document alone, you might have to guess things and in
fact you would probably end up implementing quite a different language.
On the other hand, if you are using
Python and wonder what the precise rules about a particular area of
the language are, you should definitely be able to find them here.
If you would like to see a more formal definition of the language,
maybe you could volunteer your time -- or invent a cloning machine
:-).
It is dangerous to add too many implementation details to a language
reference document -- the implementation may change, and other
implementations of the same language may work differently. On the
other hand, there is currently only one Python implementation in
widespread use (although a second one now exists!), and
its particular quirks are sometimes worth being mentioned, especially
where the implementation imposes additional limitations. Therefore,
you'll find short ``implementation notes'' sprinkled throughout the
text.
Every Python implementation comes with a number of built-in and
standard modules. These are not documented here, but in the separate
Python Library Reference (../lib/lib.html) document. A few
built-in modules are mentioned when they interact in a significant way
with the language definition.


2.3.1 Keywords

identifiers.html | identifiers.html | id-classes.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.3 Identifiers and keywords (identifiers.html)
Up:
2.3 Identifiers and keywords (identifiers.html)
Next:
2.3.2 Reserved classes of (id-classes.html)
---
## 2.3.1 Keywords
The following identifiers are used as reserved words, or
keywords of the language, and cannot be used as ordinary
identifiers. They must be spelled exactly as written here:
```text

and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
```
Note that although the identifier `as` can be used as part of the
syntax of import statements, it is not currently a reserved
word.
In some future version of Python, the identifiers `as` and
`None` will both become keywords.


5.11 Lambdas

Booleans.html | expressions.html | exprlists.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.10 Boolean operations (Booleans.html)
Up:
5. Expressions (expressions.html)
Next:
5.12 Expression lists (exprlists.html)
---
# 5.11 Lambdas
Lambda forms (lambda expressions) have the same syntactic position as
expressions. They are a shorthand to create anonymous functions; the
expression `lambda arguments : expression`
yields a function object. The unnamed object behaves like a function
object defined with
```text

def name(arguments):
return expression
```
See section 7.5 (function.html#function) for the syntax of parameter lists. Note
that functions created with lambda forms cannot contain statements.


2. Lexical analysis

notation.html | ref.html | line-structure.html | Python Reference Manual | contents.html | genindex.html
Previous:
1.1 Notation (notation.html)
Up:
Python Reference Manual (ref.html)
Next:
2.1 Line structure (line-structure.html)
---
# 2. Lexical analysis
A Python program is read by a parser. Input to the parser is a
stream of tokens, generated by the lexical analyzer. This
chapter describes how the lexical analyzer breaks a file into tokens.
Python uses the 7-bit ASCII character set for program text.
New in version 2.3:
An encoding declaration can be used to indicate that
string literals and comments use an encoding different from ASCII..
For compatibility with older versions, Python only warns if it finds
8-bit characters; those warnings should be corrected by either declaring
an explicit encoding, or using escape sequences if those bytes are binary
data, instead of characters.
The run-time character set depends on the I/O devices connected to the
program but is generally a superset of ASCII.
Future compatibility note: It may be tempting to assume that the
character set for 8-bit characters is ISO Latin-1 (an ASCII
superset that covers most western languages that use the Latin
alphabet), but it is possible that in the future Unicode text editors
will become common. These generally use the UTF-8 encoding, which is
also an ASCII superset, but with very different use for the
characters with ordinals 128-255. While there is no consensus on this
subject yet, it is unwise to assume either Latin-1 or UTF-8, even
though the current implementation appears to favor Latin-1. This
applies both to the source character set and the run-time character
set.


2.1 Line structure

lexical.html | lexical.html | logical.html | Python Reference Manual | contents.html | genindex.html
Previous:
2. Lexical analysis (lexical.html)
Up:
2. Lexical analysis (lexical.html)
Next:
2.1.1 Logical lines (logical.html)
---
# 2.1 Line structure
A Python program is divided into a number of logical lines.


5.2.4 List displays

parenthesized.html | atoms.html | dict.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.2.3 Parenthesized forms (parenthesized.html)
Up:
5.2 Atoms (atoms.html)
Next:
5.2.5 Dictionary displays (dict.html)
---
## 5.2.4 List displays
A list display is a possibly empty series of expressions enclosed in
square brackets:
`test` | ::= | `and_test ( "or" and_test )*
| lambda_form`
`testlist` | ::= | `test ( "," test )* [ "," ]`
`list_display` | ::= | `"[" [ listmaker ] "]"`
`listmaker` | ::= | `expression ( list_for | ( "," expression )* [","] )`
`list_iter` | ::= | `list_for | list_if`
`list_for` | ::= | `"for" expression_list "in" testlist [ list_iter ]`
`list_if` | ::= | `"if" test [ list_iter ]`
Download entire grammar as text. (grammar.txt)
A list display yields a new list object. Its contents are specified
by providing either a list of expressions or a list comprehension.
When a comma-separated list of expressions is supplied, its elements are
evaluated from left to right and placed into the list object in that
order. When a list comprehension is supplied, it consists of a
single expression followed by at least one for clause and zero or
more for or if clauses. In this
case, the elements of the new list are those that would be produced
by considering each of the for or if clauses a block,
nesting from
left to right, and evaluating the expression to produce a list element
each time the innermost block is reached.


2.4 Literals

id-classes.html | lexical.html | strings.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.3.2 Reserved classes of (id-classes.html)
Up:
2. Lexical analysis (lexical.html)
Next:
2.4.1 String literals (strings.html)
---
# 2.4 Literals
Literals are notations for constant values of some built-in types.


2.1.1 Logical lines

line-structure.html | line-structure.html | physical.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1 Line structure (line-structure.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.2 Physical lines (physical.html)
---
## 2.1.1 Logical lines
The end of
a logical line is represented by the token NEWLINE. Statements cannot
cross logical line boundaries except where NEWLINE is allowed by the
syntax (e.g., between statements in compound statements).
A logical line is constructed from one or more physical lines
by following the explicit or implicit line joining rules.


3.3.3 Customizing class creation

slots.html | specialnames.html | callable-types.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.2.4 __slots__ (slots.html)
Up:
3.3 Special method names (specialnames.html)
Next:
3.3.4 Emulating callable objects (callable-types.html)
---
## 3.3.3 Customizing class creation
By default, new-style classes are constructed using type().
A class definition is read into a separate namespace and the value
of class name is bound to the result of `type(name, bases, dict)`.
When the class definition is read, if __metaclass__ is defined
then the callable assigned to it will be called instead of type().
The allows classes or functions to be written which monitor or alter the class
creation process:
- Modifying the class dictionary prior to the class being created.
- Returning an instance of another class - essentially performing
the role of a factory function.
The appropriate metaclass is determined by the following precedence rules:
- If `dict['__metaclass__']` exists, it is used.
- Otherwise, if there is at least one base class, its metaclass is used
(this looks for a __class__ attribute first and if not found, uses its
type).
- Otherwise, if a global variable named __metaclass__ exists, it is used.
- Otherwise, the old-style, classic metaclass (types.ClassType) is used.
The potential uses for metaclasses are boundless. Some ideas that have
been explored including logging, interface checking, automatic delegation,
automatic property creation, proxies, frameworks, and automatic resource
locking/synchronization.


4.1 Naming and binding

execmodel.html | execmodel.html | dynamic-features.html | Python Reference Manual | contents.html | genindex.html
Previous:
4. Execution model (execmodel.html)
Up:
4. Execution model (execmodel.html)
Next:
4.1.1 Interaction with dynamic (dynamic-features.html)
---
# 4.1 Naming and binding
Namesrefer to objects. Names are introduced by
name binding operations. Each occurrence of a name in the program
text refers to the binding of that name
established in the innermost function block containing the use.
A blockis a piece of Python program text that is
executed as a unit. The following are blocks: a module, a function
body, and a class definition. Each command typed interactively is a
block. A script file (a file given as standard input to the
interpreter or specified on the interpreter command line the first
argument) is a code block. A script command (a command specified on
the interpreter command line with the `-c' option) is a code
block. The file read by the built-in function execfile()
is a code block. The string argument passed to the built-in function
eval() and to the exec statement is a code block.
The expression read and evaluated by the built-in function
input() is a code block.
A code block is executed in an execution
frame. A frame contains some
administrative information (used for debugging) and determines where
and how execution continues after the code block's execution has
completed.
A scopedefines the visibility of a name within a
block. If a local variable is defined in a block, its scope includes
that block. If the definition occurs in a function block, the scope
extends to any blocks contained within the defining one, unless a
contained block introduces a different binding for the name. The
scope of names defined in a class block is limited to the class block;
it does not extend to the code blocks of methods.
When a name is used in a code block, it is resolved using the nearest
enclosing scope. The set of all such scopes visible to a code block
is called the block's environment.
If a name is bound in a block, it is a local variable of that block.
If a name is bound at the module level, it is a global variable. (The
variables of the module code block are local and global.) If a
variable is used in a code block but not defined there, it is a
free variable.
When a name is not found at all, a
NameError exception is raised. If the name
refers to a local variable that has not been bound, a
UnboundLocalErrorexception is
raised. UnboundLocalError is a subclass of
NameError.
The following constructs bind names: formal parameters to functions,
import statements, class and function definitions (these
bind the class or function name in the defining block), and targets
that are identifiers if occurring in an assignment, for loop
header, or in the second position of an except clause
header. The import statement of the form ``"from
...import *"'' binds all names defined in the
imported module, except those beginning with an underscore. This form
may only be used at the module level.
A target occurring in a del statement is also considered bound
for this purpose (though the actual semantics are to unbind the
name). It is illegal to unbind a name that is referenced by an
enclosing scope; the compiler will report a SyntaxError.
Each assignment or import statement occurs within a block defined by a
class or function definition or at the module level (the top-level
code block).
If a name binding operation occurs anywhere within a code block, all
uses of the name within the block are treated as references to the
current block. This can lead to errors when a name is used within a
block before it is bound.
The previous rule is a subtle. Python lacks declarations and allows
name binding operations to occur anywhere within a code block. The
local variables of a code block can be determined by scanning the
entire text of the block for name binding operations.
If the global statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name in the
top-level namespace. Names are resolved in the top-level namespace by
searching the global namespace, i.e. the namespace of the module
containing the code block, and the builtin namespace, the namespace of
the module __builtin__. The global namespace is searched
first. If the name is not found there, the builtin namespace is
searched. The global statement must precede all uses of the name.
The built-in namespace associated with the execution of a code block
is actually found by looking up the name `__builtins__` in its
global namespace; this should be a dictionary or a module (in the
latter case the module's dictionary is used). Normally, the
`__builtins__` namespace is the dictionary of the built-in module
__builtin__ (note: no `s'). If it isn't, restricted
execution mode is in effect.
The namespace for a module is automatically created the first time a
module is imported. The main module for a script is always called
__main__.
The global statement has the same scope as a name binding operation
in the same block. If the nearest enclosing scope for a free variable
contains a global statement, the free variable is treated as a global.
A class definition is an executable statement that may use and define
names. These references follow the normal rules for name resolution.
The namespace of the class definition becomes the attribute dictionary
of the class. Names defined at the class scope are not visible in
methods.


attribute-access.html | attribute-access.html | descriptors.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.2 Customizing attribute access (attribute-access.html)
Up:
3.3.2 Customizing attribute access (attribute-access.html)
Next:
3.3.2.2 Implementing Descriptors (descriptors.html)
---
### 3.3.2.1 More attribute access for new-style classes
The following methods only apply to new-style classes.


A. History and License

expression-input.html | ref.html | node104.html | Python Reference Manual | contents.html | genindex.html
Previous:
8.4 Expression input (expression-input.html)
Up:
Python Reference Manual (ref.html)
Next:
A.1 History of the (node104.html)
---
# A. History and License


A.1 History of the software

node103.html | node103.html | node105.html | Python Reference Manual | contents.html | genindex.html
Previous:
A. History and License (node103.html)
Up:
A. History and License (node103.html)
Next:
A.2 Terms and conditions (node105.html)
---
# A.1 History of the software
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations (now Zope
Corporation; see http://www.zope.com/). In 2001, the Python
Software Foundation (PSF, see http://www.python.org/psf/) was
formed, a non-profit organization created specifically to own
Python-related Intellectual Property. Zope Corporation is a
sponsoring member of the PSF.
All Python releases are Open Source (see
http://www.opensource.org/ for the Open Source Definition).
Historically, most, but not all, Python releases have also been
GPL-compatible; the table below summarizes the various releases.
Note:
GPL-compatible doesn't mean that we're distributing
Python under the GPL. All Python licenses, unlike the GPL, let you
distribute a modified version without making your changes open source.
The GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.


node104.html | node103.html | genindex.html | Python Reference Manual | contents.html | genindex.html
Previous:
A.1 History of the (node104.html)
Up:
A. History and License (node103.html)
Next:
---
# 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.1 Notation

introduction.html | introduction.html | lexical.html | Python Reference Manual | contents.html | genindex.html
Previous:
1. Introduction (introduction.html)
Up:
1. Introduction (introduction.html)
Next:
2. Lexical analysis (lexical.html)
---
# 1.1 Notation
The descriptions of lexical analysis and syntax use a modified BNF
grammar notation. This uses the following style of definition:
```text

name: lc_letter (lc_letter | "_")*
lc_letter: "a"..."z"
```
The first line says that a `name` is an `lc_letter` followed by
a sequence of zero or more `lc_letter`s and underscores. An
`lc_letter` in turn is any of the single characters "a"
through "z". (This rule is actually adhered to for the
names defined in lexical and grammar rules in this document.)
Each rule begins with a name (which is the name defined by the rule)
and a colon. A vertical bar (`|`) is used to separate
alternatives; it is the least binding operator in this notation. A
star (`*`) means zero or more repetitions of the preceding item;
likewise, a plus (`+`) means one or more repetitions, and a
phrase enclosed in square brackets (`[ ]`) means zero or one
occurrences (in other words, the enclosed phrase is optional). The
`*` and `+` operators bind as tightly as possible;
parentheses are used for grouping. Literal strings are enclosed in
quotes. White space is only meaningful to separate tokens.
Rules are normally contained on a single line; rules with many
alternatives may be formatted alternatively with each line after the
first beginning with a vertical bar.
In lexical definitions (as the example above), two more conventions
are used: Two literal characters separated by three dots mean a choice
of any single character in the given (inclusive) range of ASCII
characters. A phrase between angular brackets (`<...>`) gives an
informal description of the symbol defined; e.g., this could be used
to describe the notion of `control character' if needed.


2.4.3 Numeric literals

string-catenation.html | literals.html | integers.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.4.2 String literal concatenation (string-catenation.html)
Up:
2.4 Literals (literals.html)
Next:
2.4.4 Integer and long (integers.html)
---
## 2.4.3 Numeric literals
There are four types of numeric literals: plain integers, long
integers, floating point numbers, and imaginary numbers. There are no
complex literals (complex numbers can be formed by adding a real
number and an imaginary number).
Note that numeric literals do not include a sign; a phrase like
`-1` is actually an expression composed of the unary operator
``-`' and the literal `1`.


3.3.7 Emulating numeric types

sequence-methods.html | specialnames.html | coercion-rules.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.6 Additional methods for (sequence-methods.html)
Up:
3.3 Special method names (specialnames.html)
Next:
3.3.8 Coercion rules (coercion-rules.html)
---
## 3.3.7 Emulating numeric types
The following methods can be defined to emulate numeric objects.
Methods corresponding to operations that are not supported by the
particular kind of number implemented (e.g., bitwise operations for
non-integral numbers) should be left undefined.


3.1 Objects, values and types

datamodel.html | datamodel.html | types.html | Python Reference Manual | contents.html | genindex.html
Previous:
3. Data model (datamodel.html)
Up:
3. Data model (datamodel.html)
Next:
3.2 The standard type (types.html)
---
# 3.1 Objects, values and types
Objects are Python's abstraction for data. All data in a Python
program is represented by objects or by relations between objects.
(In a sense, and in conformance to Von Neumann's model of a
``stored program computer,'' code is also represented by objects.)
Every object has an identity, a type and a value. An object's
identity never changes once it has been created; you may think
of it as the object's address in memory. The `is' operator
compares the identity of two objects; the
id() function returns an integer
representing its identity (currently implemented as its address).
An object's type is
also unchangeable.3.1 (#foot2276)An object's type determines the operations that the object
supports (e.g., ``does it have a length?'') and also defines the
possible values for objects of that type. The
type() function returns an object's type
(which is an object itself). The value of some
objects can change. Objects whose value can change are said to be
mutable; objects whose value is unchangeable once they are
created are called immutable.
(The value of an immutable container object that contains a reference
to a mutable object can change when the latter's value is changed;
however the container is still considered immutable, because the
collection of objects it contains cannot be changed. So, immutability
is not strictly the same as having an unchangeable value, it is more
subtle.)
An object's mutability is determined by its type; for instance,
numbers, strings and tuples are immutable, while dictionaries and
lists are mutable.
Objects are never explicitly destroyed; however, when they become
unreachable they may be garbage-collected. An implementation is
allowed to postpone garbage collection or omit it altogether -- it is
a matter of implementation quality how garbage collection is
implemented, as long as no objects are collected that are still
reachable. (Implementation note: the current implementation uses a
reference-counting scheme with (optional) delayed detection of
cyclically linked garbage, which collects most objects as soon as they
become unreachable, but is not guaranteed to collect garbage
containing circular references. See the
Python Library Reference (../lib/module-gc.html) for
information on controlling the collection of cyclic garbage.)
Note that the use of the implementation's tracing or debugging
facilities may keep objects alive that would normally be collectable.
Also note that catching an exception with a
`try...except' statement may keep objects alive.
Some objects contain references to ``external'' resources such as open
files or windows. It is understood that these resources are freed
when the object is garbage-collected, but since garbage collection is
not guaranteed to happen, such objects also provide an explicit way to
release the external resource, usually a close() method.
Programs are strongly recommended to explicitly close such
objects. The `try...finally' statement provides
a convenient way to do this.
Some objects contain references to other objects; these are called
containers. Examples of containers are tuples, lists and
dictionaries. The references are part of a container's value. In
most cases, when we talk about the value of a container, we imply the
values, not the identities of the contained objects; however, when we
talk about the mutability of a container, only the identities of
the immediately contained objects are implied. So, if an immutable
container (like a tuple)
contains a reference to a mutable object, its value changes
if that mutable object is changed.
Types affect almost all aspects of object behavior. Even the importance
of object identity is affected in some sense: for immutable types,
operations that compute new values may actually return a reference to
any existing object with the same type and value, while for mutable
objects this is not allowed. E.g., after
"a = 1; b = 1",
`a` and `b` may or may not refer to the same object with the
value one, depending on the implementation, but after
"c = []; d = []", `c` and `d`
are guaranteed to refer to two different, unique, newly created empty
lists.
(Note that "c = d = []" assigns the same object to both
`c` and `d`.)


2.5 Operators

imaginary.html | lexical.html | delimiters.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.4.6 Imaginary literals (imaginary.html)
Up:
2. Lexical analysis (lexical.html)
Next:
2.6 Delimiters (delimiters.html)
---
# 2.5 Operators
The following tokens are operators:
```text

+ - * ** / // %
<< >> & | ^ ~
< > <= >= == != <>
```
The comparison operators `<>` and `!=` are alternate
spellings of the same operator. `!=` is the preferred spelling;
`<>` is obsolescent.


2.2 Other tokens

whitespace.html | lexical.html | identifiers.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.9 Whitespace between tokens (whitespace.html)
Up:
2. Lexical analysis (lexical.html)
Next:
2.3 Identifiers and keywords (identifiers.html)
---
# 2.2 Other tokens
Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
exist: identifiers, keywords, literals,
operators, and delimiters.
Whitespace characters (other than line terminators, discussed earlier)
are not tokens, but serve to delimit tokens.
Where
ambiguity exists, a token comprises the longest possible string that
forms a legal token, when read from left to right.


5.2.3 Parenthesized forms

atom-literals.html | atoms.html | lists.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.2.2 Literals (atom-literals.html)
Up:
5.2 Atoms (atoms.html)
Next:
5.2.4 List displays (lists.html)
---
## 5.2.3 Parenthesized forms
A parenthesized form is an optional expression list enclosed in
parentheses:
`parenth_form` | ::= | `"(" [ expression_list ] ")"`
Download entire grammar as text. (grammar.txt)
A parenthesized expression list yields whatever that expression list
yields: if the list contains at least one comma, it yields a tuple;
otherwise, it yields the single expression that makes up the
expression list.
An empty pair of parentheses yields an empty tuple object. Since
tuples are immutable, the rules for literals apply (i.e., two
occurrences of the empty tuple may or may not yield the same object).
Note that tuples are not formed by the parentheses, but rather by use
of the comma operator. The exception is the empty tuple, for which
parentheses are required -- allowing unparenthesized ``nothing''
in expressions would cause ambiguities and allow common typos to
pass uncaught.


6.4 The pass statement

augassign.html | simple.html | del.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.3.1 Augmented assignment statements (augassign.html)
Up:
6. Simple statements (simple.html)
Next:
6.5 The del statement (del.html)
---
# 6.4 The pass statement
`pass_stmt` | ::= | `"pass"`
Download entire grammar as text. (grammar.txt)
pass is a null operation -- when it is executed, nothing
happens. It is useful as a placeholder when a statement is
required syntactically, but no code needs to be executed, for example:
```text

def f(arg): pass # a function that does nothing (yet)

class C: pass # a class with no methods (yet)
```


2.1.2 Physical lines

logical.html | line-structure.html | comments.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.1 Logical lines (logical.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.1.3 Comments (comments.html)
---
## 2.1.2 Physical lines
A physical line ends in whatever the current platform's convention is
for terminating lines. On Unix, this is the ASCII LF (linefeed)
character. On Windows, it is the ASCII sequence CR LF (return
followed by linefeed). On Macintosh, it is the ASCII CR (return)
character.


5.4 The power operator

calls.html | expressions.html | unary.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.3.4 Calls (calls.html)
Up:
5. Expressions (expressions.html)
Next:
5.5 Unary arithmetic operations (unary.html)
---
# 5.4 The power operator
The power operator binds more tightly than unary operators on its
left; it binds less tightly than unary operators on its right. The
syntax is:
`power` | ::= | `primary ["**" u_expr ]`
Download entire grammar as text. (grammar.txt)
Thus, in an unparenthesized sequence of power and unary operators, the
operators are evaluated from right to left (this does not constrain
the evaluation order for the operands).
The power operator has the same semantics as the built-in
pow() function, when called with two arguments: it yields
its left argument raised to the power of its right argument. The
numeric arguments are first converted to a common type. The result
type is that of the arguments after coercion.
With mixed operand types, the coercion rules for binary arithmetic
operators apply. For int and long int operands, the result has the
same type as the operands (after coercion) unless the second argument
is negative; in that case, all arguments are converted to float and a
float result is delivered. For example, `10**2` returns `100`,
but `10**-2` returns `0.01`. (This last feature was added in
Python 2.2. In Python 2.1 and before, if both arguments were of integer
types and the second argument was negative, an exception was raised).
Raising `0.0` to a negative power results in a
ZeroDivisionError. Raising a negative number to a
fractional power results in a ValueError.


5.3 Primaries

string-conversions.html | expressions.html | attribute-references.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.2.6 String conversions (string-conversions.html)
Up:
5. Expressions (expressions.html)
Next:
5.3.1 Attribute references (attribute-references.html)
---
# 5.3 Primaries
Primaries represent the most tightly bound operations of the language.
Their syntax is:
`primary` | ::= | `atom | attributeref | subscription | slicing | call`
Download entire grammar as text. (grammar.txt)


6.6 The print statement

del.html | simple.html | return.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.5 The del statement (del.html)
Up:
6. Simple statements (simple.html)
Next:
6.7 The return statement (return.html)
---
# 6.6 The print statement
`print_stmt` | ::= | `"print" ( [ expression ("," expression )* [ "," ] ]`
`| "> > " expression [ ("," expression )+ [ "," ] ] )`
Download entire grammar as text. (grammar.txt)
print evaluates each expression in turn and writes the
resulting object to standard output (see below). If an object is not
a string, it is first converted to a string using the rules for string
conversions. The (resulting or original) string is then written. A
space is written before each object is (converted and) written, unless
the output system believes it is positioned at the beginning of a
line. This is the case (1) when no characters have yet been written
to standard output, (2) when the last character written to standard
output is "\n", or (3) when the last write operation on
standard output was not a print statement. (In some cases
it may be functional to write an empty string to standard output for
this reason.) Note:
Objects which act like file objects but which are
not the built-in file objects often do not properly emulate this
aspect of the file object's behavior, so it is best not to rely on
this.
A "\n" character is written at the end, unless the
print statement ends with a comma. This is the only action
if the statement contains just the keyword print.
Standard output is defined as the file object named `stdout`
in the built-in module sys. If no such object exists, or if
it does not have a write() method, a RuntimeError
exception is raised.
print also has an extendedform, defined by the second portion of the syntax described above.
This form is sometimes referred to as ``print chevron.''
In this form, the first expression after the `>``>` must
evaluate to a ``file-like'' object, specifically an object that has a
write() method as described above. With this extended form,
the subsequent expressions are printed to this file object. If the
first expression evaluates to `None`, then `sys.stdout` is
used as the file for output.


8.1 Complete Python programs

top-level.html | top-level.html | file-input.html | Python Reference Manual | contents.html | genindex.html
Previous:
8. Top-level components (top-level.html)
Up:
8. Top-level components (top-level.html)
Next:
8.2 File input (file-input.html)
---
# 8.1 Complete Python programs
While a language specification need not prescribe how the language
interpreter is invoked, it is useful to have a notion of a complete
Python program. A complete Python program is executed in a minimally
initialized environment: all built-in and standard modules are
available, but none have been initialized, except for sys
(various system services), __builtin__ (built-in functions,
exceptions and `None`) and __main__. The latter is used
to provide the local and global namespace for execution of the
complete program.
The syntax for a complete Python program is that for file input,
described in the next section.
The interpreter may also be invoked in interactive mode; in this case,
it does not read and execute a complete program but reads and executes
one statement (possibly compound) at a time. The initial environment
is identical to that of a complete program; each statement is executed
in the namespace of __main__.
Under Unix, a complete program can be passed to the interpreter in
three forms: with the -c string command line option, as a
file passed as the first command line argument, or as standard input.
If the file or standard input is a tty device, the interpreter enters
interactive mode; otherwise, it executes the file as a complete
program.


6.9 The raise statement

yield.html | simple.html | break.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.8 The yield statement (yield.html)
Up:
6. Simple statements (simple.html)
Next:
6.10 The break statement (break.html)
---
# 6.9 The raise statement
`raise_stmt` | ::= | `"raise" [ expression ["," expression ["," expression ]]]`
Download entire grammar as text. (grammar.txt)
If no expressions are present, raise re-raises the last
expression that was active in the current scope. If no exception is
active in the current scope, an exception is raised indicating this error.
Otherwise, raise evaluates the expressions to get three
objects, using `None` as the value of omitted expressions. The
first two objects are used to determine the type and
value of the exception.
If the first object is an instance, the type of the exception is the
class of the instance, the instance itself is the value, and the
second object must be `None`.
If the first object is a class, it becomes the type of the exception.
The second object is used to determine the exception value: If it is
an instance of the class, the instance becomes the exception value.
If the second object is a tuple, it is used as the argument list for
the class constructor; if it is `None`, an empty argument list is
used, and any other object is treated as a single argument to the
constructor. The instance so created by calling the constructor is
used as the exception value.
If a third object is present and not `None`, it must be a
traceback object (see section 3.2 (types.html#traceback)), and
it is substituted instead of the current location as the place where
the exception occurred. If the third object is present and not a
traceback object or `None`, a TypeError exception is
raised. The three-expression form of raise is useful to
re-raise an exception transparently in an except clause, but
raise with no expressions should be preferred if the
exception to be re-raised was the most recently active exception in
the current scope.
Additional information on exceptions can be found in
section 4.2 (exceptions.html#exceptions), and information about handling exceptions is
in section 7.4 (try.html#try).


Python Reference Manual

../index.html | front.html | Python Reference Manual | contents.html | genindex.html
Up:
Python Documentation Index (../index.html)
Next:
Front Matter (front.html)
---
# Python Reference Manual
Guido van Rossum
Fred L. Drake, Jr., editor
PythonLabs
Email: python-docs@python.org
Release 2.3
July 29, 2003


6.7 The return statement

print.html | simple.html | yield.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.6 The print statement (print.html)
Up:
6. Simple statements (simple.html)
Next:
6.8 The yield statement (yield.html)
---
# 6.7 The return statement
`return_stmt` | ::= | `"return" [ expression_list ]`
Download entire grammar as text. (grammar.txt)
return may only occur syntactically nested in a function
definition, not within a nested class definition.
If an expression list is present, it is evaluated, else `None`
is substituted.
return leaves the current function call with the expression
list (or `None`) as return value.
When return passes control out of a try statement
with a finally clause, that finally clause is executed
before really leaving the function.
In a generator function, the return statement is not allowed
to include an expression_list (exprlists.html#tok-expression_list). In that context, a bare
return indicates that the generator is done and will cause
StopIteration to be raised.


sequence-types.html | specialnames.html | numeric-types.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.5 Emulating container types (sequence-types.html)
Up:
3.3 Special method names (specialnames.html)
Next:
3.3.7 Emulating numeric types (numeric-types.html)
---
## 3.3.6 Additional methods for emulation of sequence types
The following optional methods can be defined to further emulate sequence
objects. Immutable sequences methods should at most only define
__getslice__(); mutable sequences might define all three
three methods.
Notice that these methods are only invoked when a single slice with a
single colon is used, and the slice method is available. For slice
operations involving extended slice notation, or in absence of the
slice methods, __getitem__(), __setitem__() or
__delitem__() is called with a slice object as argument.
The following example demonstrate how to make your program or module
compatible with earlier versions of Python (assuming that methods
__getitem__(), __setitem__() and __delitem__()
support slice objects as arguments):
```text

class MyClass:
...
def __getitem__(self, index):
...
def __setitem__(self, index, value):
...
def __delitem__(self, index):
...

if sys.version_info < (2, 0):
# They won't be defined if version is at least 2.0 final

def __getslice__(self, i, j):
return self[max(0, i):max(0, j):]
def __setslice__(self, i, j, seq):
self[max(0, i):max(0, j):] = seq
def __delslice__(self, i, j):
del self[max(0, i):max(0, j):]
...
```
Note the calls to max(); these are necessary because of
the handling of negative indices before the
__*slice__() methods are called. When negative indexes are
used, the __*item__() methods receive them as provided, but
the __*slice__() methods get a ``cooked'' form of the index
values. For each negative index value, the length of the sequence is
added to the index before calling the method (which may still result
in a negative index); this is the customary handling of negative
indexes by the built-in sequence types, and the __*item__()
methods are expected to do this as well. However, since they should
already be doing that, negative indexes cannot be passed in; they must
be be constrained to the bounds of the sequence before being passed to
the __*item__() methods.
Calling `max(0, i)` conveniently returns the proper value.


3.3.5 Emulating container types

callable-types.html | specialnames.html | sequence-methods.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.4 Emulating callable objects (callable-types.html)
Up:
3.3 Special method names (specialnames.html)
Next:
3.3.6 Additional methods for (sequence-methods.html)
---
## 3.3.5 Emulating container types
The following methods can be defined to implement container
objects. Containers usually are sequences (such as lists or tuples)
or mappings (like dictionaries), but can represent other containers as
well. The first set of methods is used either to emulate a
sequence or to emulate a mapping; the difference is that for a
sequence, the allowable keys should be the integers k for which
`0 <= k < N` where N is the length of the
sequence, or slice objects, which define a range of items. (For backwards
compatibility, the method __getslice__() (see below) can also be
defined to handle simple, but not extended slices.) It is also recommended
that mappings provide the methods keys(), values(),
items(), has_key(), get(), clear(),
setdefault(), iterkeys(), itervalues(),
iteritems(), pop(), popitem(),
copy(), and update() behaving similar to those for
Python's standard dictionary objects. The UserDict module
provides a DictMixin class to help create those methods
from a base set of __getitem__(), __setitem__(),
__delitem__(), and keys().
Mutable sequences should provide
methods append(), count(), index(),
extend(),
insert(), pop(), remove(), reverse()
and sort(), like Python standard list objects. Finally,
sequence types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
__add__(), __radd__(), __iadd__(),
__mul__(), __rmul__() and __imul__() described
below; they should not define __coerce__() or other numerical
operators. It is recommended that both mappings and sequences
implement the __contains__() method to allow efficient use of
the `in` operator; for mappings, `in` should be equivalent
of has_key(); for sequences, it should search through the
values. It is further recommended that both mappings and sequences
implement the __iter__() method to allow efficient iteration
through the container; for mappings, __iter__() should be
the same as iterkeys(); for sequences, it should iterate
through the values.
The membership test operators (in and not in) are
normally implemented as an iteration through a sequence. However,
container objects can supply the following special method with a more
efficient implementation, which also does not require the object be a
sequence.


5.7 Shifting operations

binary.html | expressions.html | bitwise.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.6 Binary arithmetic operations (binary.html)
Up:
5. Expressions (expressions.html)
Next:
5.8 Binary bit-wise operations (bitwise.html)
---
# 5.7 Shifting operations
The shifting operations have lower priority than the arithmetic
operations:
`shift_expr` | ::= | `a_expr | shift_expr ( "«" | "»" ) a_expr`
Download entire grammar as text. (grammar.txt)
These operators accept plain or long integers as arguments. The
arguments are converted to a common type. They shift the first
argument to the left or right by the number of bits given by the
second argument.
A right shift by n bits is defined as division by
`pow(2, n )`. A left shift by n bits is defined as
multiplication with `pow(2, n )`; for plain integers there is
no overflow check so in that case the operation drops bits and flips
the sign if the result is not less than `pow(2,31)` in absolute
value. Negative shift counts raise a ValueError
exception.


6. Simple statements

summary.html | ref.html | exprstmts.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.14 Summary (summary.html)
Up:
Python Reference Manual (ref.html)
Next:
6.1 Expression statements (exprstmts.html)
---
# 6. Simple statements
Simple statements are comprised within a single logical line.
Several simple statements may occur on a single line separated
by semicolons. The syntax for simple statements is:
`simple_stmt` | ::= | `expression_stmt`
`| assert_stmt`
`| assignment_stmt`
`| augmented_assignment_stmt`
`| pass_stmt`
`| del_stmt`
`| print_stmt`
`| return_stmt`
`| yield_stmt`
`| raise_stmt`
`| break_stmt`
`| continue_stmt`
`| import_stmt`
`| global_stmt`
`| exec_stmt`
Download entire grammar as text. (grammar.txt)


5.3.3 Slicings

subscriptions.html | primaries.html | calls.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.3.2 Subscriptions (subscriptions.html)
Up:
5.3 Primaries (primaries.html)
Next:
5.3.4 Calls (calls.html)
---
## 5.3.3 Slicings
A slicing selects a range of items in a sequence object (e.g., a
string, tuple or list). Slicings may be used as expressions or as
targets in assignment or del statements. The syntax for a slicing:
`slicing` | ::= | `simple_slicing | extended_slicing`
`simple_slicing` | ::= | `primary "[" short_slice "]"`
`extended_slicing` | ::= | `primary "[" slice_list "]"`
`slice_list` | ::= | `slice_item ("," slice_item )* [","]`
`slice_item` | ::= | `expression | proper_slice | ellipsis`
`proper_slice` | ::= | `short_slice | long_slice`
`short_slice` | ::= | `[ lower_bound ] ":" [ upper_bound ]`
`long_slice` | ::= | `short_slice ":" [ stride ]`
`lower_bound` | ::= | `expression`
`upper_bound` | ::= | `expression`
`stride` | ::= | `expression`
`ellipsis` | ::= | `"..."`
Download entire grammar as text. (grammar.txt)
There is ambiguity in the formal syntax here: anything that looks like
an expression list also looks like a slice list, so any subscription
can be interpreted as a slicing. Rather than further complicating the
syntax, this is disambiguated by defining that in this case the
interpretation as a subscription takes priority over the
interpretation as a slicing (this is the case if the slice list
contains no proper slice nor ellipses). Similarly, when the slice
list has exactly one short slice and no trailing comma, the
interpretation as a simple slicing takes priority over that as an
extended slicing.
The semantics for a simple slicing are as follows. The primary must
evaluate to a sequence object. The lower and upper bound expressions,
if present, must evaluate to plain integers; defaults are zero and the
`sys.maxint`, respectively. If either bound is negative, the
sequence's length is added to it. The slicing now selects all items
with index k such that
`i <= k < j` where i
and j are the specified lower and upper bounds. This may be an
empty sequence. It is not an error if i or j lie outside the
range of valid indexes (such items don't exist so they aren't
selected).
The semantics for an extended slicing are as follows. The primary
must evaluate to a mapping object, and it is indexed with a key that
is constructed from the slice list, as follows. If the slice list
contains at least one comma, the key is a tuple containing the
conversion of the slice items; otherwise, the conversion of the lone
slice item is the key. The conversion of a slice item that is an
expression is that expression. The conversion of an ellipsis slice
item is the built-in `Ellipsis` object. The conversion of a
proper slice is a slice object (see section 3.2 (types.html#types)) whose
start, stop and step attributes are the
values of the expressions given as lower bound, upper bound and
stride, respectively, substituting `None` for missing
expressions.


3.3.2.4 __slots__

descriptor-invocation.html | attribute-access.html | metaclasses.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.3.2.3 Invoking Descriptors (descriptor-invocation.html)
Up:
3.3.2 Customizing attribute access (attribute-access.html)
Next:
3.3.3 Customizing class creation (metaclasses.html)
---
### 3.3.2.4 __slots__
By default, instances of both old and new-style classes have a dictionary
for attribute storage. This wastes space for objects having very few instance
variables. The space consumption can become acute when creating large numbers
of instances.
The default can be overridden by defining __slots__ in a new-style class
definition. The __slots__ declaration takes a sequence of instance
variables and reserves just enough space in each instance to hold a value
for each variable. Space is saved because __dict__ is not created for
each instance.
Notes on using __slots__
- Without a __dict__ variable, instances cannot be assigned new
variables not listed in the __slots__ definition. Attempts to assign
to an unlisted variable name raises AttributeError. If dynamic
assignment of new variables is desired, then add `'__dict__'` to the
sequence of strings in the __slots__ declaration.
Changed in version 2.3:
Previously, adding `'__dict__'` to the __slots__
declaration would not enable the assignment of new attributes not
specifically listed in the sequence of instance variable names.
- Without a __weakref__ variable for each instance, classes
defining __slots__ do not support weak references to its instances.
If weak reference support is needed, then add `'__weakref__'` to the
sequence of strings in the __slots__ declaration.
Changed in version 2.3:
Previously, adding `'__weakref__'` to the __slots__
declaration would not enable support for weak references.
- __slots__ are implemented at the class level by creating
descriptors (3.3.2 (descriptors.html#descriptors)) for each variable name. As a result,
class attributes cannot be used to set default values for instance
variables defined by __slots__; otherwise, the class attribute would
overwrite the descriptor assignment.
- If a class defines a slot also defined in a base class, the instance
variable defined by the base class slot is inaccessible (except by retrieving
its descriptor directly from the base class). This renders the meaning of the
program undefined. In the future, a check may be added to prevent this.
- The action of a __slots__ declaration is limited to the class
where it is defined. As a result, subclasses will have a __dict__
unless they also define __slots__.
- __slots__ do not work for classes derived from ``variable-length''
built-in types such as long, str and tuple.
- Any non-string iterable may be assigned to __slots__.
Mappings may also be used; however, in the future, special meaning may
be assigned to the values corresponding to each key.


3.3 Special method names

types.html | datamodel.html | customization.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.2 The standard type (types.html)
Up:
3. Data model (datamodel.html)
Next:
3.3.1 Basic customization (customization.html)
---
# 3.3 Special method names
A class can implement certain operations that are invoked by special
syntax (such as arithmetic operations or subscripting and slicing) by
defining methods with special names.This is Python's approach to operator overloading, allowing
classes to define their own behavior with respect to language
operators. For instance, if a class defines
a method named __getitem__(), and `x` is an instance of
this class, then `x[i]` is equivalent to
`x.__getitem__(i)`. Except where mentioned, attempts to execute
an operation raise an exception when no appropriate method is defined.
When implementing a class that emulates any built-in type, it is
important that the emulation only be implemented to the degree that it
makes sense for the object being modelled. For example, some
sequences may work well with retrieval of individual elements, but
extracting a slice may not make sense. (One example of this is the
NodeList interface in the W3C's Document Object Model.)


2.4.2 String literal concatenation

strings.html | literals.html | numbers.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.4.1 String literals (strings.html)
Up:
2.4 Literals (literals.html)
Next:
2.4.3 Numeric literals (numbers.html)
---
## 2.4.2 String literal concatenation
Multiple adjacent string literals (delimited by whitespace), possibly
using different quoting conventions, are allowed, and their meaning is
the same as their concatenation. Thus, `"hello" 'world'` is
equivalent to `"helloworld"`. This feature can be used to reduce
the number of backslashes needed, to split long strings conveniently
across long lines, or even to add comments to parts of strings, for
example:
```text

re.compile("[A-Za-z_]" # letter or underscore
"[A-Za-z0-9_]*" # letter, digit or underscore
)
```
Note that this feature is defined at the syntactical level, but
implemented at compile time. The `+' operator must be used to
concatenate string expressions at run time. Also note that literal
concatenation can use different quoting styles for each component
(even mixing raw strings and triple quoted strings).


5.2.6 String conversions

dict.html | atoms.html | primaries.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.2.5 Dictionary displays (dict.html)
Up:
5.2 Atoms (atoms.html)
Next:
5.3 Primaries (primaries.html)
---
## 5.2.6 String conversions
A string conversion is an expression list enclosed in reverse (a.k.a.
backward) quotes:
`string_conversion` | ::= | `"`" expression_list "`"`
Download entire grammar as text. (grammar.txt)
A string conversion evaluates the contained expression list and
converts the resulting object into a string according to rules
specific to its type.
If the object is a string, a number, `None`, or a tuple, list or
dictionary containing only objects whose type is one of these, the
resulting string is a valid Python expression which can be passed to
the built-in function eval() to yield an expression with the
same value (or an approximation, if floating point numbers are
involved).
(In particular, converting a string adds quotes around it and converts
``funny'' characters to escape sequences that are safe to print.)
Recursive objects (for example, lists or dictionaries that contain a
reference to themselves, directly or indirectly) use "..." to
indicate a recursive reference, and the result cannot be passed to
eval() to get an equal value (SyntaxError will
be raised instead).
The built-in function repr() performs exactly the same
conversion in its argument as enclosing it in parentheses and reverse
quotes does. The built-in function str() performs a
similar but more user-friendly conversion.