4.1 Standard Module string

node64.html
node62.html
node62.html
node1.html
node270.html
---
# 4.1 Standard Module string
This module defines some constants useful for checking character
classes and some useful string functions. See the module
re for string functions based on regular expressions.
The constants defined in this module are are:
The functions defined in this module are:
This module is implemented in Python. Much of its functionality has
been reimplemented in the built-in module strop. However, you
should never import the latter module directly. When
string discovers that strop exists, it transparently
replaces parts of itself with the implementation from strop.
After initialization, there is no overhead in using
string instead of strop.
---
node64.html
node62.html
node62.html
node1.html
node270.html
guido@python.org


4.2 Built-in Module re

node65.html
node62.html
node63.html
node1.html
node270.html
---
# 4.2 Built-in Module re
This module provides regular expression matching operations similar to
those found in Perl. It's 8-bit clean: both patterns and strings may
contain null bytes and characters whose high bit is set. It is always
available.
Regular expressions use the backslash character (\) to
indicate special forms or to allow special characters to be used
without invoking their special meaning. This collides with Python's
usage of the same character for the same purpose in string literals;
for example, to match a literal backslash, one might have to write
\\\\ as the pattern string, because the regular expression
must be \\, and each backslash must be expressed as
\\ inside a regular Python string literal.
The solution is to use Python's raw string notation for regular
expression patterns; backslashes are not handled in any special way in
a string literal prefixed with 'r'. So r"\n" is a two
character string containing a backslash and the letter 'n', while
"\n" is a one-character string containing a newline. Usually
patterns will be expressed in Python code using this raw string notation.
---
- Regular Expression Syntax (node65.html#SECTION005210000000000000000)
Module Contents (node66.html#SECTION005220000000000000000)
Regular Expression Objects (node67.html#SECTION005230000000000000000)
Match Objects (node68.html#SECTION005240000000000000000)
---
guido@python.org


Regular Expression Syntax

node66.html
node64.html
node64.html
node1.html
node270.html
---
## Regular Expression Syntax
A regular expression (or RE) specifies a set of strings that matches
it; the functions in this module let you check if a particular string
matches a given regular expression (or if a given regular expression
matches a particular string, which comes down to the same thing).
Regular expressions can be concatenated to form new regular
expressions; if A and B are both regular expressions,
then AB is also an regular expression. If a string p
matches A and another string q matches B, the string pq
will match AB. Thus, complex expressions can easily be constructed
from simpler primitive expressions like the ones described here. For
details of the theory and implementation of regular expressions,
consult the Friedl book referenced below, or almost any textbook about
compiler construction.
A brief explanation of the format of regular expressions follows.
Regular expressions can contain both special and ordinary characters.
Most ordinary characters, like 'A', 'a', or '0',
are the simplest regular expressions; they simply match themselves.
You can concatenate ordinary characters, so 'last' matches the
characters 'last'. (In the rest of this section, we'll write RE's in
this special font, usually without quotes, and strings to be
matched 'in single quotes'.)
Some characters, like | or (, are special. Special
characters either stand for classes of ordinary characters, or affect
how the regular expressions around them are interpreted.
The special characters are:
The special sequences consist of '\' and a character from the
list below. If the ordinary character is not on the list, then the
resulting RE will match the second character. For example,
\$ matches the character '$'.
---
node66.html
node64.html
node64.html
node1.html
node270.html
guido@python.org


Module Contents

node67.html
node64.html
node65.html
node1.html
node270.html
---
## Module Contents
The module defines the following functions and constants, and an exception:
---
node67.html
node64.html
node65.html
node1.html
node270.html
guido@python.org


Regular Expression Objects

node68.html
node64.html
node66.html
node1.html
node270.html
---
## Regular Expression Objects
Compiled regular expression objects support the following methods and
attributes:
---
node68.html
node64.html
node66.html
node1.html
node270.html
guido@python.org


Match Objects

node69.html
node64.html
node67.html
node1.html
node270.html
---
## Match Objects
MatchObject instances support the following methods and attributes:
See Also:
Jeffrey Friedl, Mastering Regular Expressions,
O'Reilly. The Python material in this book dates from before the
re module, but it covers writing good regular expression
patterns in great detail.
---
node69.html
node64.html
node67.html
node1.html
node270.html
guido@python.org


4.3 Built-in Module regex

node70.html
node62.html
node68.html
node1.html
node270.html
---
# 4.3 Built-in Module regex
This module provides regular expression matching operations similar to
those found in Emacs.
Obsolescence note:
This module is obsolete as of Python version 1.5; it is still being
maintained because much existing code still uses it. All new code in
need of regular expressions should use the new
re module, which supports the more powerful
and regular Perl-style regular expressions. Existing code should be
converted. The standard library module
reconvert helps in converting
regex style regular expressions to re
style regular expressions. (For more conversion help, see the URL
http://starship.skyport.net/crew/amk/regex/regex-to-re.html.)
By default the patterns are Emacs-style regular expressions
(with one exception). There is
a way to change the syntax to match that of several well-known
Unix utilities. The exception is that Emacs' `\s'
pattern is not supported, since the original implementation references
the Emacs syntax tables.
This module is 8-bit clean: both patterns and strings may contain null
bytes and characters whose high bit is set.
Please note: There is a little-known fact about Python string
literals which means that you don't usually have to worry about
doubling backslashes, even though they are used to escape special
characters in string literals as well as in regular expressions. This
is because Python doesn't remove backslashes from string literals if
they are followed by an unrecognized escape character.
However, if you want to include a literal backslash in a
regular expression represented as a string literal, you have to
quadruple it or enclose it in a singleton character class.
E.g. to extract LaTeX `\section{
...}' headers from a document, you can use this pattern:
'[\]section{\(.*\)}'. Another exception:
the escape sequece `\b' is significant in string literals
(where it means the ASCII bell character) as well as in Emacs regular
expressions (where it stands for a word boundary), so in order to
search for a word boundary, you should use the pattern '\\b'.
Similarly, a backslash followed by a digit 0-7 should be doubled to
avoid interpretation as an octal escape.
---
- Regular Expressions (node70.html#SECTION005310000000000000000)
Module Contents (node71.html#SECTION005320000000000000000)
---
node70.html
node62.html
node68.html
node1.html
node270.html
guido@python.org


Comparisons

node8.html
node4.html
node6.html
node1.html
node270.html
---
## Comparisons
Comparison operations are supported by all objects. They all have the
same priority (which is higher than that of the Boolean operations).
Comparisons can be chained arbitrarily, e.g. x < y <= z is
equivalent to x < y and y <= z, except that y is
evaluated only once (but in both cases z is not evaluated at
all when x < y is found to be false).
This table summarizes the comparison operations:
Operation | Meaning | Notes
,
Notes:
Objects of different types, except different numeric types, never
compare equal; such objects are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (e.g., windows) support only a degenerate
notion of comparison where any two objects of that type are unequal.
Again, such objects are ordered arbitrarily but consistently.
(Implementation note: objects of different types except numbers are
ordered by their type names; objects of the same types that don't
support proper comparison are ordered by their address.)
Two more operations with the same syntactic priority, in and
not in, are supported only by sequence types (below).
---
node8.html
node4.html
node6.html
node1.html
node270.html
guido@python.org


Regular Expressions

node71.html
node69.html
node69.html
node1.html
node270.html
---
## Regular Expressions
A regular expression (or RE) specifies a set of strings that matches
it; the functions in this module let you check if a particular string
matches a given regular expression (or if a given regular expression
matches a particular string, which comes down to the same thing).
Regular expressions can be concatenated to form new regular
expressions; if A and B are both regular expressions,
then AB is also an regular expression. If a string p
matches A and another string q matches B, the string pq
will match AB. Thus, complex expressions can easily be constructed
from simpler ones like the primitives described here. For details of
the theory and implementation of regular expressions, consult almost
any textbook about compiler construction.
A brief explanation of the format of regular expressions follows.
Regular expressions can contain both special and ordinary characters.
Ordinary characters, like 'A', 'a', or '0', are
the simplest regular expressions; they simply match themselves. You
can concatenate ordinary characters, so 'last' matches the
characters 'last'. (In the rest of this section, we'll write RE's in
this special font, usually without quotes, and strings to be
matched 'in single quotes'.)
Special characters either stand for classes of ordinary characters, or
affect how the regular expressions around them are interpreted.
The special characters are:
The special sequences consist of '\' and a character
from the list below. If the ordinary character is not on the list,
then the resulting RE will match the second character. For example,
\$ matches the character '$'. Ones where the backslash
should be doubled in string literals are indicated.
---
node71.html
node69.html
node69.html
node1.html
node270.html
guido@python.org


Module Contents

node72.html
node69.html
node70.html
node1.html
node270.html
---
## Module Contents
The module defines these functions, and an exception:
,
Compiled regular expression objects support these methods:
,
Compiled regular expressions support these data attributes:
---
node72.html
node69.html
node70.html
node1.html
node270.html
guido@python.org


4.4 Standard Module regsub

node73.html
node62.html
node71.html
node1.html
node270.html
---
# 4.4 Standard Module regsub
This module defines a number of functions useful for working with
regular expressions (see built-in module regex).
Warning: these functions are not thread-safe.
Obsolescence note:
This module is obsolete as of Python version 1.5; it is still being
maintained because much existing code still uses it. All new code in
need of regular expressions should use the new re module, which
supports the more powerful and regular Perl-style regular expressions.
Existing code should be converted. The standard library module
reconvert helps in converting regex style regular
expressions to re style regular expressions. (For more
conversion help, see the URL
http://starship.skyport.net/crew/amk/regex/regex-to-re.html.)
---
node73.html
node62.html
node71.html
node1.html
node270.html
guido@python.org


4.5 Built-in Module struct

node74.html
node62.html
node72.html
node1.html
node270.html
---
# 4.5 Built-in Module struct
This module performs conversions between Python values and C
structs represented as Python strings. It uses format strings
(explained below) as compact descriptions of the lay-out of the C
structs and the intended conversion to/from Python values.
See also built-in module array.
The module defines the following exception and functions:
Format characters have the following meaning; the conversion between C
and Python values should be obvious given their types:
Format | C | Python
A format character may be preceded by an integral repeat count; e.g.\
the format string '4h' means exactly the same as 'hhhh'.
Whitespace characters between formats are ignored; a count and its
format must not contain whitespace though.
For the 's' format character, the count is interpreted as the
size of the string, not a repeat count like for the other format
characters; e.g. '10s' means a single 10-byte string, while
'10c' means 10 characters. For packing, the string is
truncated or padded with null bytes as appropriate to make it fit.
For unpacking, the resulting string always has exactly the specified
number of bytes. As a special case, '0s' means a single, empty
string (while '0c' means 0 characters).
For the 'I' and 'L' format characters, the return
value is a Python long integer.
By default, C numbers are represented in the machine's native format
and byte order, and properly aligned by skipping pad bytes if
necessary (according to the rules used by the C compiler).
Alternatively, the first character of the format string can be used to
indicate the byte order, size and alignment of the packed data,
according to the following table:
Character | Byte order | Size and alignment
If the first character is not one of these, '@' is assumed.
Native byte order is big-endian or little-endian, depending on the
host system (e.g. Motorola and Sun are big-endian; Intel and DEC are
little-endian).
Native size and alignment are determined using the C compiler's sizeof
expression. This is always combined with native byte order.
Standard size and alignment are as follows: no alignment is required
for any type (so you have to use pad bytes); short is 2 bytes; int and
long are 4 bytes. Float and double are 32-bit and 64-bit IEEE floating
point numbers, respectively.
Note the difference between '@' and '=': both use native
byte order, but the size and alignment of the latter is standardized.
The form '!' is available for those poor souls who claim they
can't remember whether network byte order is big-endian or
little-endian.
There is no way to indicate non-native byte order (i.e. force
byte-swapping); use the appropriate choice of '<' or
'>'.
Examples (all using native byte order, size and alignment, on a
big-endian machine):
```text
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\000\001\000\002\000\000\000\003'
>>> unpack('hhl', '\000\001\000\002\000\000\000\003')
(1, 2, 3)
>>> calcsize('hhl')
8
>>>
```
Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
repeat count of zero, e.g. the format 'llh0l' specifies two
pad bytes at the end, assuming longs are aligned on 4-byte boundaries.
(This only works when native size and alignment are in effect;
standard size and alignment does not enforce any alignment.)
---
node74.html
node62.html
node72.html
node1.html
node270.html
guido@python.org


4.6 Standard Module StringIO

node75.html
node62.html
node73.html
node1.html
node270.html
---
# 4.6 Standard Module StringIO
This module implements a file-like class, StringIO,
that reads and writes a string buffer (also known as memory
files). See the description on file objects for operations.
When a StringIO object is created, it can be initialized
to an existing string by passing the string to the constructor.
If no string is given, the StringIO will start empty.
The method getvalue() can be called to retrieve the entire
contents of the ``file'' at any time before the StringIO
object's close() method is called. Calling close() will
free the memory buffer.
---
guido@python.org


4.7 Built-in Module soundex

node76.html
node62.html
node74.html
node1.html
node270.html
---
# 4.7 Built-in Module soundex
The soundex algorithm takes an English word, and returns an
easily-computed hash of it; this hash is intended to be the same for
words that sound alike. This module provides an interface to the
soundex algorithm.
Note that the soundex algorithm is quite simple-minded, and isn't
perfect by any measure. Its main purpose is to help looking up names
in databases, when the name may be misspelled -- soundex hashes common
misspellings together.
---
guido@python.org


5 Miscellaneous Services

node77.html
lib.html
node75.html
node1.html
node270.html
---
# 5 Miscellaneous Services
The modules described in this chapter provide miscellaneous services
that are available in all Python versions. Here's an overview:
---
- 5.1 Built-in Module math (node77.html#SECTION006100000000000000000)
5.2 Built-in Module cmath (node78.html#SECTION006200000000000000000)
5.3 Standard Module whrandom (node79.html#SECTION006300000000000000000)
5.4 Standard Module random (node80.html#SECTION006400000000000000000)
5.5 Standard Module rand (node81.html#SECTION006500000000000000000)
5.6 Built-in Module array (node82.html#SECTION006600000000000000000)
---
guido@python.org


5.1 Built-in Module math

node78.html
node76.html
node76.html
node1.html
node270.html
---
# 5.1 Built-in Module math
This module is always available.
It provides access to the mathematical functions defined by the C
standard.
They are:
Note that frexp() and modf() have a different
call/return pattern than their C equivalents: they take a single
argument and return a pair of values, rather than returning their
second return value through an `output parameter' (there is no such
thing in Python).
The module also defines two mathematical constants:
See Also:
cmath (Complex number versions of many of these functions.)
---
node78.html
node76.html
node76.html
node1.html
node270.html
guido@python.org


5.2 Built-in Module cmath

node79.html
node76.html
node77.html
node1.html
node270.html
---
# 5.2 Built-in Module cmath
This module is always available.
It provides access to mathematical functions for complex numbers.
The functions are:
The module also defines two mathematical constants:
Note that the selection of functions is similar, but not identical, to
that in module math. The reason for having
two modules is, that some users aren't interested in complex numbers,
and perhaps don't even know what they are. They would rather have
math.sqrt(-1) raise an exception than return a complex number.
Also note that the functions defined in cmath always return a
complex number, even if the answer can be expressed as a real number
(in which case the complex number has an imaginary part of zero).
---
node79.html
node76.html
node77.html
node1.html
node270.html
guido@python.org


5.3 Standard Module whrandom

node80.html
node76.html
node78.html
node1.html
node270.html
---
# 5.3 Standard Module whrandom
This module implements a Wichmann-Hill pseudo-random number generator
class that is also named whrandom. Instances of the
whrandom class have the following methods:
When imported, the whrandom module also creates an instance of
the whrandom class, and makes the methods of that instance
available at the module level. Therefore one can write either
N = whrandom.random() or:
```text
generator = whrandom.whrandom()
N = generator.random()
```
See Also:
random (generators for various random distributions)
Wichmann, B. A. & Hill, I. D., ``Algorithm AS 183:
An efficient and portable pseudo-random number generator'',
Applied Statistics 31 (1982) 188-190
---
guido@python.org


Numeric Types

node9.html
node4.html
node7.html
node1.html
node270.html
---
## Numeric Types
There are four numeric types: plain integers, long integers,
floating point numbers, and complex numbers.
Plain integers (also just called integers)
are implemented using long in C, which gives them at least 32
bits of precision. Long integers have unlimited precision. Floating
point numbers are implemented using double in C. All bets on
their precision are off unless you happen to know the machine you are
working with.
Complex numbers have a real and imaginary part, which are both
implemented using double in C. To extract these parts from
a complex number z, use z.real and z.imag.
Numbers are created by numeric literals or as the result of built-in
functions and operators. Unadorned integer literals (including hex
and octal numbers) yield plain integers. Integer literals with an `L'
or `l' suffix yield long integers
(`L' is preferred because `1l' looks too much like eleven!).
Numeric literals containing a decimal point or an exponent sign yield
floating point numbers. Appending `j' or `J' to a numeric
literal yields a complex number.
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
``smaller'' type is converted to that of the other, where plain
integer is smaller than long integer is smaller than floating point is
smaller than complex.
Comparisons between numbers of mixed type use the same rule.footnode.html#965
The functions int(), long(), float(),
and complex() can be used
to coerce numbers to a specific type.
All numeric types support the following operations, sorted by
ascending priority (operations in the same box have the same
priority; all numeric operations have a higher priority than
comparison operations):
Operation | Result | Notes
,
Notes:
---
- Bit-string Operations on Integer Types (node9.html#SECTION003141000000000000000)
---
node9.html
node4.html
node7.html
node1.html
node270.html
guido@python.org


5.4 Standard Module random

node81.html
node76.html
node79.html
node1.html
node270.html
---
# 5.4 Standard Module random
This module implements pseudo-random number generators for various
distributions: on the real line, there are functions to compute normal
or Gaussian, lognormal, negative exponential, gamma, and beta
distributions. For generating distribution of angles, the circular
uniform and von Mises distributions are available.
The module exports the following functions, which are exactly
equivalent to those in the whrandom module: choice,
randint, random, uniform. See the documentation
for the whrandom module for these functions.
The following functions specific to the random module are also
defined, and all return real values. Function parameters are named
after the corresponding variables in the distribution's equation, as
used in common mathematical practice; most of these equations can be
found in any statistics text.
See Also:
whrandom (the standard Python random number generator)
---
node81.html
node76.html
node79.html
node1.html
node270.html
guido@python.org


5.5 Standard Module rand

node82.html
node76.html
node80.html
node1.html
node270.html
---
# 5.5 Standard Module rand
The rand module simulates the C library's rand()
interface, though the results aren't necessarily compatible with any
given library's implementation. While still supported for
compatibility, the rand module is now considered obsolete; if
possible, use the whrandom module instead.
See Also:
whrandom (the standard Python random number generator)
---
guido@python.org


5.6 Built-in Module array

node83.html
node76.html
node81.html
node1.html
node270.html
---
# 5.6 Built-in Module array
This module defines a new object type which can efficiently represent
an array of basic values: characters, integers, floating point
numbers. Arrays are sequence types and behave very much like lists,
except that the type of objects stored in them is constrained. The
type is specified at object creation time by using a type code,
which is a single character. The following type codes are defined:
Typecode | Type | Minimal size in bytes
The actual representation of values is determined by the machine
architecture (strictly speaking, by the C implementation). The actual
size can be accessed through the itemsize attribute. The values
stored for 'L' and 'I' items will be represented as
Python long integers when retrieved, because Python's plain integer
type can't represent the full range of C's unsigned (long) integers.
See also built-in module struct.
The module defines the following function:
Array objects support the following data items and methods:
When an array object is printed or converted to a string, it is
represented as array(typecode, initializer). The
initializer is omitted if the array is empty, otherwise it is a
string if the typecode is 'c', otherwise it is a list of
numbers. The string is guaranteed to be able to be converted back to
an array with the same type and value using reverse quotes
(``). Examples:
```text
array('l')
array('c', 'hello world')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
```
---
node83.html
node76.html
node81.html
node1.html
node270.html
guido@python.org


6 Generic Operating System Services

node84.html
lib.html
node82.html
node1.html
node270.html
---
# 6 Generic Operating System Services
The modules described in this chapter provide interfaces to operating
system features that are available on (almost) all operating systems,
such as files and a clock. The interfaces are generally modelled
after the Unix or C interfaces but they are available on most other
systems as well. Here's an overview:
---
- 6.1 Standard Module os (node84.html#SECTION007100000000000000000)
6.2 Built-in Module time (node85.html#SECTION007200000000000000000)
6.3 Standard Module getopt (node86.html#SECTION007300000000000000000)
6.4 Standard Module tempfile (node87.html#SECTION007400000000000000000)
6.5 Standard Module errno (node88.html#SECTION007500000000000000000)
6.6 Standard Module glob (node89.html#SECTION007600000000000000000)
6.7 Standard Module fnmatch (node90.html#SECTION007700000000000000000)
6.8 Standard Module locale (node91.html#SECTION007800000000000000000)
---
guido@python.org


6.1 Standard Module os

node85.html
node83.html
node83.html
node1.html
node270.html
---
# 6.1 Standard Module os
This module provides a more portable way of using operating system
(OS) dependent functionality than importing an OS dependent built-in
module like posix.
When the optional built-in module posix is available, this
module exports the same functions and data as posix; otherwise,
it searches for an OS dependent built-in module like mac and
exports the same functions and data as found there. The design of all
Python's built-in OS dependent modules is such that as long as the same
functionality is available, it uses the same interface; e.g., the
function os.stat(file) returns stat info about a file in a
format compatible with the POSIX interface.
Extensions peculiar to a particular OS are also available through the
os module, but using them is of course a threat to portability!
Note that after the first time os is imported, there is no
performance penalty in using functions from os instead of
directly from the OS dependent built-in module, so there should be
no reason not to use os!
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by os:
(The functions os.execv() and execve() are not
documented here, since they are implemented by the OS dependent
module. If the OS dependent module doesn't define either of these,
the functions that rely on it will raise an exception. They are
documented in the section on module posix, together with all
other functions that os imports from the OS dependent module.)
---
node85.html
node83.html
node83.html
node1.html
node270.html
guido@python.org


6.2 Built-in Module time

node86.html
node83.html
node84.html
node1.html
node270.html
---
# 6.2 Built-in Module time
This module provides various time-related functions.
It is always available.
An explanation of some terminology and conventions is in order.
- The ``epoch'' is the point where the time starts. On January 1st of that
year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the
epoch is 1970. To find out what the epoch is, look at gmtime(0).UTC is Coordinated Universal Time (formerly known as Greenwich Mean
Time). The acronym UTC is not a mistake but a compromise between
English and French.DST is Daylight Saving Time, an adjustment of the timezone by
(usually) one hour during part of the year. DST rules are magic
(determined by local law) and can change from year to year. The C
library has a table containing the local rules (often it is read from
a system file for flexibility) and is the only source of True Wisdom
in this respect.The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is expressed.
E.g. on most Unix systems, the clock ``ticks'' only 50 or 100 times a
second, and on the Mac, times are only accurate to whole seconds.On the other hand, the precision of time() and sleep()
is better than their Unix equivalents: times are expressed as floating
point numbers, time() returns the most accurate time available
(using Unix gettimeofday() where available), and sleep()
will accept a time with a nonzero fraction (Unix select() is
used to implement this, where available).The time tuple as returned by gmtime() and localtime(),
or as accpted by mktime() is a tuple of 9
integers: year (e.g. 1993), month (1-12), day (1-31), hour
(0-23), minute (0-59), second (0-59), weekday (0-6, monday is 0),
Julian day (1-366) and daylight savings flag (-1, 0 or 1).
Note that unlike the C structure, the month value is a range of 1-12, not
0-11. A year value less than 100 will typically be silently converted to
1900 plus the year value. A -1 argument as daylight savings flag, passed to
mktime() will usually result in the correct daylight savings
state to be filled in.
The module defines the following functions and data items:
---
node86.html
node83.html
node84.html
node1.html
node270.html
guido@python.org


6.3 Standard Module getopt

node87.html
node83.html
node85.html
node1.html
node270.html
---
# 6.3 Standard Module getopt
This module helps scripts to parse the command line arguments in
sys.argv.
It supports the same conventions as the Unix
getopt()
function (including the special meanings of arguments of the form
`-' and `--').
Long options similar to those supported by
GNU software may be used as well via an optional third argument.
It defines the function
getopt.getopt(args, options [, long_options])
and the exception
getopt.error.
The first argument to
getopt()
is the argument list passed to the script with its first element
chopped off (i.e.,
sys.argv[1:]).
The second argument is the string of option letters that the
script wants to recognize, with options that require an argument
followed by a colon (i.e., the same format that Unix
getopt()
uses).
The third option, if specified, is a list of strings with the names of
the long options which should be supported. The leading '--'
characters should not be included in the option name. Options which
require an argument should be followed by an equal sign ('=').
The return value consists of two elements: the first is a list of
option-and-value pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice of the
first argument).
Each option-and-value pair returned has the option as its first element,
prefixed with a hyphen (e.g.,
'-x'),
and the option argument as its second element, or an empty string if the
option has no argument.
The options occur in the list in the same order in which they were
found, thus allowing multiple occurrences. Long and short options may
be mixed.
An example using only Unix style options:
```text
>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>>
```
Using long option names is equally easy:
```text
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = string.split(s)
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']
>>>
```
The exception
getopt.error
is raised when an unrecognized option is found in the argument list or
when an option requiring an argument is given none.
The argument to the exception is a string indicating the cause of the
error. For long options, an argument given to an option which does
not require one will also cause this exception to be raised.
---
node87.html
node83.html
node85.html
node1.html
node270.html
guido@python.org


6.4 Standard Module tempfile

node88.html
node83.html
node86.html
node1.html
node270.html
---
# 6.4 Standard Module tempfile
This module generates temporary file names. It is not Unix specific,
but it may require some help on non-Unix systems.
Note: the modules does not create temporary files, nor does it
automatically remove them when the current process exits or dies.
The module defines a single user-callable function:
The module uses two global variables that tell it how to construct a
temporary name. The caller may assign values to them; by default they
are initialized at the first call to mktemp().
Warning: if a Unix process uses mktemp(), then calls
fork() and both parent and child continue to use
mktemp(), the processes will generate conflicting temporary
names. To resolve this, the child process should assign None
to template, to force recomputing the default on the next call
to mktemp().
---
node88.html
node83.html
node86.html
node1.html
node270.html
guido@python.org


6.5 Standard Module errno

node89.html
node83.html
node87.html
node1.html
node270.html
---
# 6.5 Standard Module errno
This module makes available standard errno system symbols.
The value of each symbol is the corresponding integer value.
The names and descriptions are borrowed from `linux/include/errno.h',
which should be pretty all-inclusive. Of the following list, symbols
that are not used on the current platform are not defined by the
module.
The module also defines the dictionary variable errorcode which
maps numeric error codes back to their symbol names, so that e.g.
errno.errorcode[errno.EPERM] == 'EPERM'. To translate a
numeric error code to an error message, use os.strerror().
Symbols available can include:
---
node89.html
node83.html
node87.html
node1.html
node270.html
guido@python.org


6.6 Standard Module glob

node90.html
node83.html
node88.html
node1.html
node270.html
---
# 6.6 Standard Module glob
The glob module finds all the pathnames matching a specified
pattern according to the rules used by the Unix shell. No tilde
expansion is done, but *, ?, and character ranges
expressed with [] will be correctly matched. This is done by
using the os.listdir() and fnmatch.fnmatch()
functions in concert, and not by actually invoking a subshell. (For
tilde and shell variable expansion, use os.path.expanduser()
and os.path.expandvars().)
For example, consider a directory containing only the following files:
`1.gif', `2.txt', and `card.gif'. glob.glob()
will produce the following results. Notice how any leading components
of the path are preserved.
```text
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
```
---
guido@python.org


Bit-string Operations on Integer Types

node10.html
node8.html
node8.html
node1.html
node270.html
---
### Bit-string Operations on Integer Types
Plain and long integer types support additional operations that make
sense only for bit-strings. Negative numbers are treated as their 2's
complement value (for long integers, this assumes a sufficiently large
number of bits that no overflow occurs during the operation).
The priorities of the binary bit-wise operations are all lower than
the numeric operations and higher than the comparisons; the unary
operation `~' has the same priority as the other unary numeric
operations (`+' and `-').
This table lists the bit-string operations sorted in ascending
priority (operations in the same box have the same priority):
Operation | Result | Notes
,
Notes:
---
guido@python.org


6.7 Standard Module fnmatch

node91.html
node83.html
node89.html
node1.html
node270.html
---
# 6.7 Standard Module fnmatch
This module provides support for Unix shell-style wildcards, which
are not the same as regular expressions (which are documented
in the re module). The special characters
used in shell-style wildcards are:
Note that the filename separator ('/' on Unix) is not
special to this module. See module glob
for pathname expansion (glob uses fnmatch() to
match filename segments).
See Also:
glob (Shell-style path expansion)
---
guido@python.org


6.8 Standard Module locale

node92.html
node83.html
node90.html
node1.html
node270.html
---
# 6.8 Standard Module locale
The locale module opens access to the POSIX locale database
and functionality. The POSIX locale mechanism allows applications
to integrate certain cultural aspects into an applications, without
requiring the programmer to know all the specifics of each country
where the software is executed.
The locale module is implemented on top of the _locale
module, which in turn uses an ANSI C locale implementation if
available.
The locale module defines the following functions:
Example:
```text
>>> import locale
>>> locale.open(locale.LC_ALL,"de") #setting locale to German
>>> locale.strcoll("f\344n","foo") #comparing a string containing an umlaut
>>> can.close()
```
---
node92.html
node83.html
node90.html
node1.html
node270.html
guido@python.org


7 Optional Operating System Services

node93.html
lib.html
node91.html
node1.html
node270.html
---
# 7 Optional Operating System Services
The modules described in this chapter provide interfaces to operating
system features that are available on selected operating systems only.
The interfaces are generally modelled after the Unix or C
interfaces but they are available on some other systems as well
(e.g. Windows or NT). Here's an overview:
---
- 7.1 Built-in Module signal (node93.html#SECTION008100000000000000000)
7.2 Built-in Module socket (node94.html#SECTION008200000000000000000)
- Socket Objects (node95.html#SECTION008210000000000000000)
Example (node96.html#SECTION008220000000000000000)
7.3 Built-in Module select (node97.html#SECTION008300000000000000000)
7.4 Built-in Module thread (node98.html#SECTION008400000000000000000)
7.5 Standard Module Queue (node99.html#SECTION008500000000000000000)
- Queue Objects (node100.html#SECTION008510000000000000000)
7.6 Standard Modules anydbm and dumbdbm (node101.html#SECTION008600000000000000000)
7.7 Standard Module whichdb (node102.html#SECTION008700000000000000000)
7.8 Built-in Module zlib (node103.html#SECTION008800000000000000000)
7.9 Built-in Module gzip (node104.html#SECTION008900000000000000000)
---
guido@python.org


7.1 Built-in Module signal

node94.html
node92.html
node92.html
node1.html
node270.html
---
# 7.1 Built-in Module signal
This module provides mechanisms to use signal handlers in Python.
Some general rules for working with signals handlers:
- A handler for a particular signal, once set, remains installed until
it is explicitly reset (i.e. Python emulates the BSD style interface
regardless of the underlying implementation), with the exception of
the handler for SIGCHLD, which follows the underlying
implementation.There is no way to ``block'' signals temporarily from critical
sections (since this is not supported by all Unix flavors).Although Python signal handlers are called asynchronously as far as
the Python user is concerned, they can only occur between the
``atomic'' instructions of the Python interpreter. This means that
signals arriving during long calculations implemented purely in C
(e.g. regular expression matches on large bodies of text) may be
delayed for an arbitrary amount of time.When a signal arrives during an I/O operation, it is possible that the
I/O operation raises an exception after the signal handler returns.
This is dependent on the underlying Unix system's semantics regarding
interrupted system calls.Because the C signal handler always returns, it makes little sense to
catch synchronous errors like SIGFPE or SIGSEGV.Python installs a small number of signal handlers by default:
SIGPIPE is ignored (so write errors on pipes and sockets can be
reported as ordinary Python exceptions), SIGINT is translated
into a KeyboardInterrupt exception, and SIGTERM is
caught so that necessary cleanup (especially sys.exitfunc) can
be performed before actually terminating. All of these can be
overridden.Some care must be taken if both signals and threads are used in the
same program. The fundamental thing to remember in using signals and
threads simultaneously is: always perform signal() operations
in the main thread of execution. Any thread can perform an
alarm(), getsignal(), or pause();
only the main thread can set a new signal handler, and the main thread
will be the only one to receive signals (this is enforced by the
Python signal module, even if the underlying thread
implementation supports sending signals to individual threads). This
means that signals can't be used as a means of interthread
communication. Use locks instead.
The variables defined in the signal module are:
The signal module defines the following functions:
---
node94.html
node92.html
node92.html
node1.html
node270.html
guido@python.org


7.2 Built-in Module socket

node95.html
node92.html
node93.html
node1.html
node270.html
---
# 7.2 Built-in Module socket
This module provides access to the BSD socket interface.
It is available on Unix systems that support this interface.
For an introduction to socket programming (in C), see the following
papers: An Introductory 4.3BSD Interprocess Communication
Tutorial, by Stuart Sechrest and An Advanced 4.3BSD Interprocess
Communication Tutorial, by Samuel J. Leffler et al, both in the
Unix Programmer's Manual, Supplementary Documents 1 (sections PS1:7
and PS1:8). The Unix manual pages for the various socket-related
system calls are also a valuable source of information on the details of
socket semantics.
The Python interface is a straightforward transliteration of the
Unix system call and library interface for sockets to Python's
object-oriented style: the socket() function returns a
socket object whose methods implement the various socket system
calls. Parameter types are somewhat higher-level than in the C
interface: as with read() and write() operations on Python
files, buffer allocation on receive operations is automatic, and
buffer length is implicit on send operations.
Socket addresses are represented as a single string for the
AF_UNIX address family and as a pair
(host, port) for the AF_INET address family,
where host is a string representing
either a hostname in Internet domain notation like
'daring.cwi.nl' or an IP address like '100.50.200.5',
and port is an integral port number. Other address families are
currently not supported. The address format required by a particular
socket object is automatically selected based on the address family
specified when the socket object was created.
For IP addresses, two special forms are accepted instead of a host
address: the empty string represents INADDR_ANY, and the string
"<broadcast>" represents INADDR_BROADCAST.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error socket.error.
Non-blocking mode is supported through the setblocking()
method.
The module socket exports the following constants and functions:
---
- Socket Objects (node95.html#SECTION008210000000000000000)
Example (node96.html#SECTION008220000000000000000)
---
node95.html
node92.html
node93.html
node1.html
node270.html
guido@python.org


Socket Objects

node96.html
node94.html
node94.html
node1.html
node270.html
---
## Socket Objects
,
Socket objects have the following methods. Except for
makefile() these correspond to Unix system calls applicable to
sockets.
Note that there are no methods read() or write(); use
recv() and send() without flags argument instead.
---
node96.html
node94.html
node94.html
node1.html
node270.html
guido@python.org


Example

node97.html
node94.html
node95.html
node1.html
node270.html
---
## Example
Here are two minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it. Note that a server must perform the
sequence socket, bind, listen, accept
(possibly repeating the accept to service more than one client),
while a client only needs the sequence socket, connect.
Also note that the server does not send/receive on the
socket it is listening on but on the new socket returned by
accept.
```text
# Echo server program
from socket import *
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged server
s = socket(AF_INET, SOCK_STREAM)
s.bind(HOST, PORT)
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
```
```text
# Echo client program
from socket import *
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket(AF_INET, SOCK_STREAM)
s.connect(HOST, PORT)
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', `data`
```
See Also:
SocketServer (classes that simplify writing network servers)
---
guido@python.org


7.3 Built-in Module select

node98.html
node92.html
node96.html
node1.html
node270.html
---
# 7.3 Built-in Module select
This module provides access to the function select available in
most Unix versions. It defines the following:
---
guido@python.org


7.4 Built-in Module thread

node99.html
node92.html
node97.html
node1.html
node270.html
---
# 7.4 Built-in Module thread
This module provides low-level primitives for working with multiple
threads (a.k.a. light-weight processes or tasks) -- multiple
threads of control sharing their global data space. For
synchronization, simple locks (a.k.a. mutexes or binary
semaphores) are provided.
The module is optional. It is supported on Windows NT and '95, SGI
IRIX, Solaris 2.x, as well as on systems that have a POSIX thread
(a.k.a. ``pthread'') implementation.
It defines the following constant and functions:
Lock objects have the following methods:
Caveats:
- Threads interact strangely with interrupts: the
KeyboardInterrupt exception will be received by an arbitrary
thread. (When the signal module is
available, interrupts always go to the main thread.)Calling sys.exit() or raising the SystemExit exception is
equivalent to calling thread.exit_thread().Not all built-in functions that may block waiting for I/O allow other
threads to run. (The most popular ones (sleep(), read(),
select()) work as expected.)It is not possible to interrupt the acquire() method on a lock
- the KeyboardInterrupt exception will happen after the lock
has been acquired.When the main thread exits, it is system defined whether the other
threads survive. On SGI IRIX using the native thread implementation,
they survive. On most other systems, they are killed without
executing ``try-finally'' clauses or executing object destructors.
When the main thread exits, it doesn't do any of its usual cleanup
(except that ``try-finally'' clauses are honored), and the standard
I/O files are not flushed.
---
node99.html
node92.html
node97.html
node1.html
node270.html
guido@python.org


7.5 Standard Module Queue

node100.html
node92.html
node98.html
node1.html
node270.html
---
# 7.5 Standard Module Queue
The Queue module implements a multi-producer, multi-consumer
FIFO queue. It is especially useful in threads programming when
information must be exchanged safely between multiple threads. The
Queue class in this module implements all the required locking
semantics. It depends on the availability of thread support in
Python.
The Queue module defines the following exception:
---
- Queue Objects (node100.html#SECTION008510000000000000000)
---
guido@python.org


Python 1.5 Reference Manual

[Next] (ref-2.html)[Contents] (ref-2.html)[Index]
# Python Reference Manual
---
Guido van Rossum
Corporation for National Research Initiatives (CNRI)
1895 Preston White Drive, Reston, Va 20191, USA
E-mail: `guido@cnri.reston.va.us`, `guido@python.org`
December 31, 1997
Release 1.5
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. For an informal introduction to the language, see the Python Tutorial. For C or C++ programmers, two additional manuals exist: Extending and Embedding the Python Interpreter describes the high-level picture of how to write a Python extension module, and the Python/C API Reference Manual describes the interfaces available to C/C++ programmers in detail.
Copyright © 1991-1995 by 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 names of Stichting Mathematisch Centrum or CWI or Corporation for National Research Initiatives or CNRI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.
While CWI is the initial source for this software, a modified version is made available by the Corporation for National Research Initiatives (CNRI) at the Internet address ftp://ftp.python.org.
STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM OR CNRI 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.
TOC
---
Python 1.5 Reference Manual - 13 JAN 1998
[Next] (ref-2.html)[Contents] (ref-2.html)[Index]
Generated with Harlequin WebMaker (http://www.harlequin.com/webmaker)


Chapter 8: Top-level components

[Next] [Previous] (ref-9.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Python 1.5 Reference Manual
# Chapter 8: Top-level components
---
The Python interpreter can get its input from a number of sources: from a script passed to it as standard input or as program argument, typed in interactively, from a module source file, etc. This chapter gives the syntax used in these cases.
## 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 name space 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 name space 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.
## 8.2 File input
All input read from non-interactive files has the same form:
```text

file_input: (NEWLINE | statement)*
```
This syntax is used in the following situations:
- when parsing a complete Python program (from a file or from a string);
when parsing a module;
when parsing a string passed to the exec statement;
## 8.3 Interactive input
Input in interactive mode is parsed using the following grammar:
```text

interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
```
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.
## 8.4 Expression input
There are two forms of expression input. Both ignore leading whitespace. The string argument to eval() must have the following form:
```text

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

input_input: expression_list NEWLINE
```
Note: to read 'raw' input line without interpretation, you can use the built-in function raw_input() or the readline() method of file objects.
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
TOC
---
Python 1.5 Reference Manual - 13 JAN 1998
[Next] [Previous] (ref-9.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Generated with Harlequin WebMaker (http://www.harlequin.com/webmaker)


ref-2

[Next] (ref-3.html)[Previous] (ref-1.html)[Top] (ref-1.html)[Index]
Python 1.5 Reference Manual
---
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
FM pgf ignored
TOC
---
Python 1.5 Reference Manual - 13 JAN 1998
[Next] (ref-3.html)[Previous] (ref-1.html)[Top] (ref-1.html)[Index]
Generated with Harlequin WebMaker (http://www.harlequin.com/webmaker)


Chapter 1: Introduction

[Next] (ref-4.html)[Previous] (ref-2.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Python 1.5 Reference Manual
# Chapter 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 have chosen 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 definitition 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, 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 document. A few built-in modules are mentioned when they interact in a significant way with the language definition.
## 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_letters 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 used 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 in 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.
Even though the notation used is almost the same, there is a big difference between the meaning of lexical and syntactic definitions: a lexical definition operates on the individual characters of the input source, while a syntax definition operates on the stream of tokens generated by the lexical analysis. All uses of BNF in the next chapter ("Lexical Analysis") are lexical definitions; uses in subsequent chapters are syntactic definitions.
TOC
---
Python 1.5 Reference Manual - 13 JAN 1998
[Next] (ref-4.html)[Previous] (ref-2.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Generated with Harlequin WebMaker (http://www.harlequin.com/webmaker)


Chapter 2: Lexical analysis

[Next] (ref-5.html)[Previous] (ref-3.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Python 1.5 Reference Manual
# Chapter 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 and string literals. 8-bit characters may be used in string literals and comments but their interpretation is platform dependent; the proper way to insert 8-bit characters in string literals is by using octal or hexadecimal escape sequences.
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
A Python program is divided in a number of logical lines.
### 2.1.1 Logical lines
The end of each 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.
### 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 DOS/Windows, it is the ASCII sequence CR LF (return followed by linefeed). On Macintosh, it is the ASCII CR (return) character.
### 2.1.3 Comments
A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax; they are not tokens.
### 2.1.4 Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:
```text

if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
return 1
```
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
### 2.1.5 Implicit line joining
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example:
```text

month_names = ['Januari', 'Februari', 'Maart', # These are the
'April', 'Mei', 'Juni', # Dutch names
'Juli', 'Augustus', 'September', # for the months
'Oktober', 'November', 'December'] # of the year
```
Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicit continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments.
### 2.1.6 Blank lines
A logical line that contains only spaces, tabs, formfeeds, and possibly a comment, is ignored (i.e., no NEWLINE token is generated), except that during interactive input of statements, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement.
### 2.1.7 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 there 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.
A formfeed character may be present at the start of the line; 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.)
### 2.1.8 Whitespace between tokens
Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., `ab` is one token, but `a` `b` is two tokens).
## 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.
## 2.3 Identifiers and keywords
Identifiers (also referred to as names) are described by the following lexical definitions:
```text

identifier: (letter|"_") (letter|digit|"_")*
letter: lowercase | uppercase
lowercase: "a"..."z"
uppercase: "A"..."Z"
digit: "0"..."9"
```
Identifiers are unlimited in length. Case is significant.
### 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
def finally in print
```
### 2.3.2 Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special meanings. These are:
(XXX need section references here.)
## 2.4 Literals
Literals are notations for constant values of some built-in types
### 2.4.1 String literals
String literals are described by the following lexical definitions:
```text

stringliteral: [rawprefix] (shortstring | longstring)
rawprefix: "r" | "R"
shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem: shortstringchar | escapeseq
longstringitem: longstringchar | escapeseq
shortstringchar: <any ASCII character except "\" or newline or the quote>
longstringchar: <any ASCII character except "\">
escapeseq: "\" <any ASCII character>
```
In plain English: String literals can be enclosed in single quotes (') or double quotes ("). They can also be enclosed in groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for backslash escape sequences.
In "long strings" (strings surrounded by sets of three quotes), unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the string. (A "quote" is the character used to open the string, i.e. either ' or ".)
Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:
In strict compatibility with Standard C, up to three octal digits are accepted, but an unlimited number of hex digits is taken to be part of the hex escape (and then the lower 8 bits of the resulting hex number are used in all current implementations...).
Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.)
When an 'r' or 'R' prefix is present, all backslashes are left in the string. For example, the string literal `r"\n"` consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, `r"\""` is a valid string literal consisting of two characters: a backslash and a double quote.
#### 2.4.1.1 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

regex.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.
### 2.4.2 Numeric literals
There are four types of numeric literals: plain integers, long integers, floating point numbers, and imaginary numbers.
#### 2.4.2.1 Integer and long integer literals
Integer and long integer literals are described by the following lexical definitions:
```text

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"
```
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 must be at most 2147483647 (i.e., the largest positive integer, using 32-bit arithmetic). Plain octal and hexadecimal literals may be as large as 4294967295, but values larger than 2147483647 are converted to a negative value by subtracting 4294967296. There is no limit for long integer literals apart from what can be stored in available memory.
Some examples of plain and long integer literals:
```text

7 2147483647 0177 0x80000000
3L 79228162514264337593543950336L 0377L 0x100000000L
```
#### 2.4.2.2 Floating point literals
Floating point literals are described by the following lexical definitions:
```text

floatnumber: pointfloat | exponentfloat
pointfloat: [intpart] fraction | intpart "."
exponentfloat: (intpart | pointfloat) exponent
intpart: nonzerodigit digit* | "0"
fraction: "." digit+
exponent: ("e"|"E") ["+"|"-"] digit+
```
Note that the integer part of a floating point number cannot look like an octal integer. 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
```
#### 2.4.2.3 Imaginary literals
Imaginary literals are described by the following lexical definitions:
```text

imagnumber: (floatnumber | intpart) ("j"|"J")
```
An imaginary literals 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 10 j .001j 1e100j 3.14e-10j
```
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.
## 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.6 Delimiters
The following tokens serve as delimiters in the grammar:
```text

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

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

@ $ ?
```
TOC
---
Python 1.5 Reference Manual - 13 JAN 1998
[Next] (ref-5.html)[Previous] (ref-3.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Generated with Harlequin WebMaker (http://www.harlequin.com/webmaker)