home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The Datafile PD-CD 5
/
DATAFILE_PDCD5.iso
/
utilities
/
p
/
python
/
!ibrowse
/
files
/
pylibi-1
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
Macintosh to JP
NeXTSTEP
RISC OS/Acorn
Shift JIS
UTF-8
Wrap
GNU Info File
|
1996-11-14
|
38.2 KB
|
1,107 lines
This is Info file pylibi, produced by Makeinfo-1.55 from the input file
lib.texi.
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system. It assumes basic
knowledge about the Python language. For an informal introduction to
the language, see the Python Tutorial. The Python Reference Manual
gives a more formal definition of the language. (These manuals are not
yet available in INFO or Texinfo format.)
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.
File: pylibi, Node: Top, Next: Introduction, Prev: (dir), Up: (dir)
The Python library
******************
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system. It assumes basic
knowledge about the Python language. For an informal introduction to
the language, see the `Python Tutorial'. The `Python Reference Manual'
gives a more formal definition of the language. (These manuals are not
yet available in INFO or Texinfo format.)
This version corresponds to Python version 1.4 (Oct 25 1996).
* Menu:
* Introduction::
* Built-in Objects::
* Python Services::
* String Services::
* Miscellaneous Services::
* Generic Operating System Services::
* Optional Operating System Services::
* The Python Debugger::
* The Python Profiler::
* Internet and WWW::
* Restricted Execution::
* Cryptographic Services::
* RISCOS ONLY::
* Function Index::
* Variable Index::
* Module Index::
* Concept Index::
File: pylibi, Node: Introduction, Next: Built-in Objects, Prev: Top, Up: Top
Introduction
************
The "Python library" contains several different kinds of components.
It contains data types that would normally be considered part of the
"core" of a language, such as numbers and lists. For these types, the
Python language core defines the form of literals and places some
constraints on their semantics, but does not fully define the
semantics. (On the other hand, the language core does define syntactic
properties like the spelling and priorities of operators.)
The library also contains built-in functions and exceptions -- objects
that can be used by all Python code without the need of an `import'
statement. Some of these are defined by the core language, but many
are not essential for the core semantics and are only described here.
The bulk of the library, however, consists of a collection of modules.
There are many ways to dissect this collection. Some modules are
written in C and built in to the Python interpreter; others are written
in Python and imported in source form. Some modules provide interfaces
that are highly specific to Python, like printing a stack trace; some
provide interfaces that are specific to particular operating systems,
like socket I/O; others provide interfaces that are specific to a
particular application domain, like the World-Wide Web. Some modules
are avaiable in all versions and ports of Python; others are only
available when the underlying system supports or requires them; yet
others are available only when a particular configuration option was
chosen at the time when Python was compiled and installed.
This manual is organized "from the inside out": it first describes the
built-in data types, then the built-in functions and exceptions, and
finally the modules, grouped in chapters of related modules. The
ordering of the chapters as well as the ordering of the modules within
each chapter is roughly from most relevant to least important.
This means that if you start reading this manual from the start, and
skip to the next chapter when you get bored, you will get a reasonable
overview of the available modules and application areas that are
supported by the Python library. Of course, you don't *have* to read
it like a novel -- you can also browse the table of contents (in front
of the manual), or look for a specific function, module or term in the
index (in the back). And finally, if you enjoy learning about random
subjects, you choose a random page number (see module `rand') and read
a section or two.
Let the show begin!
File: pylibi, Node: Built-in Objects, Next: Python Services, Prev: Introduction, Up: Top
Built-in Types, Exceptions and Functions
****************************************
Names for built-in exceptions and functions are found in a separate
symbol table. This table is searched last when the interpreter looks
up the meaning of a name, so local and global user-defined names can
override built-in names. Built-in types are described together here
for easy reference.(1)
The tables in this chapter document the priorities of operators by
listing them in order of ascending priority (within a table) and
grouping operators that have the same priority in the same box. Binary
operators of the same priority group from left to right. (Unary
operators group from right to left, but there you have no real choice.)
See Chapter 5 of the Python Reference Manual for the complete picture
on operator priorities.
* Menu:
* Types::
* Exceptions::
* Built-in Functions::
---------- Footnotes ----------
(1) Most descriptions sorely lack explanations of the exceptions that
may be raised -- this will be fixed in a future version of this manual.
File: pylibi, Node: Types, Next: Exceptions, Prev: Built-in Objects, Up: Built-in Objects
Built-in Types
==============
The following sections describe the standard types that are built into
the interpreter. These are the numeric types, sequence types, and
several others, including types themselves. There is no explicit
Boolean type; use integers instead.
Some operations are supported by several object types; in particular,
all objects can be compared, tested for truth value, and converted to a
string (with the ``...`' notation). The latter conversion is
implicitly used when an object is written by the `print' statement.
* Menu:
* Truth Value Testing::
* Boolean Operations::
* Comparisons::
* Numeric Types::
* Sequence Types::
* Mapping Types::
* Other Built-in Types::
* Special Attributes::
File: pylibi, Node: Truth Value Testing, Next: Boolean Operations, Prev: Types, Up: Types
Truth Value Testing
-------------------
Any object can be tested for truth value, for use in an `if' or `while'
condition or as operand of the Boolean operations below. The following
values are considered false:
* `None'
* zero of any numeric type, e.g., `0', `0L', `0.0'.
* any empty sequence, e.g., `''', `()', `[]'.
* any empty mapping, e.g., `{}'.
* instances of user-defined classes, if the class defines a
`__nonzero__()' or `__len__()' method, when that method returns
zero.
All other values are considered true -- so objects of many types are
always true.
Operations and built-in functions that have a Boolean result always
return `0' for false and `1' for true, unless otherwise stated.
(Important exception: the Boolean operations `or' and `and' always
return one of their operands.)
File: pylibi, Node: Boolean Operations, Next: Comparisons, Prev: Truth Value Testing, Up: Types
Boolean Operations
------------------
These are the Boolean operations, ordered by ascending priority:
*Operation*
*Result* -- *Notes*
`X or Y'
if X is false, then Y, else X -- (1)
`X and Y'
if X is false, then X, else Y -- (1)
`not X'
if X is false, then `1', else `0' -- (2)
Notes:
(1)
These only evaluate their second argument if needed for their
outcome.
(2)
`not' has a lower priority than non-Boolean operators, so e.g.
`not a == b' is interpreted as `not(a == b)', and `a == not b' is
a syntax error.
File: pylibi, Node: Comparisons, Next: Numeric Types, Prev: Boolean Operations, Up: Types
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*
`<'
strictly less than
`<='
less than or equal
`>'
strictly greater than
`>='
greater than or equal
`=='
equal
`<>'
not equal -- (1)
`!='
not equal -- (1)
`is'
object identity
`is not'
negated object identity
Notes:
(1)
`<>' and `!=' are alternate spellings for the same operator. (I
couldn't choose between ABC and C! :-)
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).
File: pylibi, Node: Numeric Types, Next: Sequence Types, Prev: Comparisons, Up: Types
Numeric Types
-------------
There are three numeric types: "plain integers", "long integers", and
"floating point 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.
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.
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.
Comparisons between numbers of mixed type use the same rule.(1) The
functions `int()', `long()' and `float()' 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*
`X + Y'
sum of X and Y
`X - Y'
difference of X and Y
`X * Y'
product of X and Y
`X / Y'
quotient of X and Y -- (1)
`X % Y'
remainder of `X / Y'
`-X'
X negated
`+X'
X unchanged
`abs(X)'
absolute value of X
`int(X)'
X converted to integer -- (2)
`long(X)'
X converted to long integer -- (2)
`float(X)'
X converted to floating point
`divmod(X, Y)'
the pair `(X / Y, X % Y)' -- (3)
`pow(X, Y)'
X to the power Y
Notes:
(1)
For (plain or long) integer division, the result is an integer.
The result is always rounded towards minus infinity: 1/2 is 0,
(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.
(2)
Conversion from floating point to (long or plain) integer may
round or truncate as in C; see functions `floor()' and `ceil()' in
module `math' for well-defined conversions.
(3)
See the section on built-in functions for an exact definition.
* Menu:
* Bit-string Operations::
---------- Footnotes ----------
(1) As a consequence, the list `[1, 2]' is considered equal to `[1.0,
2.0]', and similar for tuples.
File: pylibi, Node: Bit-string Operations, Prev: Numeric Types, Up: Numeric Types
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*
`X | Y'
bitwise "or" of X and Y
`X ^ Y'
bitwise "exclusive or" of X and Y
`X & Y'
bitwise "and" of X and Y
`X << N'
X shifted left by N bits -- (1), (2)
`X >> N'
X shifted right by N bits -- (1), (3)
`~X'
the bits of X inverted
Notes:
(1)
Negative shift counts are illegal.
(2)
A left shift by N bits is equivalent to multiplication by `pow(2,
N)' without overflow check.
(3)
A right shift by N bits is equivalent to division by `pow(2, N)'
without overflow check.
File: pylibi, Node: Sequence Types, Next: Mapping Types, Prev: Numeric Types, Up: Types
Sequence Types
--------------
There are three sequence types: strings, lists and tuples.
Strings literals are written in single or double quotes: `'xyzzy'',
`"frobozz"'. See Chapter 2 of the Python Reference Manual for more
about string literals. Lists are constructed with square brackets,
separating items with commas: `[a, b, c]'. Tuples are constructed by
the comma operator (not within square brackets), with or without
enclosing parentheses, but an empty tuple must have the enclosing
parentheses, e.g., `a, b, c' or `()'. A single item tuple must have a
trailing comma, e.g., `(d,)'.
Sequence types support the following operations. The `in' and `not,in'
operations have the same priorities as the comparison operations. The
`+' and `*' operations have the same priority as the corresponding
numeric operations.(1)
This table lists the sequence operations sorted in ascending priority
(operations in the same box have the same priority). In the table, S
and T are sequences of the same type; N, I and J are integers:
*Operation*
*Result* -- *Notes*
`X in S'
`1' if an item of S is equal to X, else `0'
`X not in S'
`0' if an item of S is equal to X, else `1'
`S + T'
the concatenation of S and T
`S * N, N * S'
N copies of S concatenated
`S[I]'
I'th item of S, origin 0 -- (1)
`S[I:J]'
slice of S from I to J -- (1), (2)
`len(S)'
length of S
`min(S)'
smallest item of S
`max(S)'
largest item of S
Notes:
(1)
If I or J is negative, the index is relative to the end of the
string, i.e., `len(S) + I' or `len(S) + J' is substituted. But
note that `-0' is still `0'.
(2)
The slice of S from I to J is defined as the sequence of items
with index K such that `I <= K < J'. If I or J is greater than
`len(S)', use `len(S)'. If I is omitted, use `0'. If J is
omitted, use `len(S)'. If I is greater than or equal to J, the
slice is empty.
* Menu:
* More String Operations::
* Mutable Sequence Types::
---------- Footnotes ----------
(1) They must have since the parser can't tell the type of the
operands.
File: pylibi, Node: More String Operations, Next: Mutable Sequence Types, Prev: Sequence Types, Up: Sequence Types
More String Operations
......................
String objects have one unique built-in operation: the `%' operator
(modulo) with a string left argument interprets this string as a C
sprintf format string to be applied to the right argument, and returns
the string resulting from this formatting operation.
The right argument should be a tuple with one item for each argument
required by the format string; if the string requires a single
argument, the right argument may also be a single non-tuple object.(1)
The following format characters are understood: %, c, s, i, d, u, o, x,
X, e, E, f, g, G. Width and precision may be a * to specify that an
integer argument specifies the actual width or precision. The flag
characters -, +, blank, # and 0 are understood. The size specifiers h,
l or L may be present but are ignored. The `%s' conversion takes any
Python object and converts it to a string using `str()' before
formatting it. The ANSI features `%p' and `%n' are not supported.
Since Python strings have an explicit length, `%s' conversions don't
assume that `'\0'' is the end of the string.
For safety reasons, floating point precisions are clipped to 50; `%f'
conversions for numbers whose absolute value is over 1e25 are replaced
by `%g' conversions.(2) All other errors raise exceptions.
If the right argument is a dictionary (or any kind of mapping), then
the formats in the string must have a parenthesized key into that
dictionary inserted immediately after the `%' character, and each
format formats the corresponding entry from the mapping. E.g.
>>> count = 2
>>> language = 'Python'
>>> print '%(language)s has %(count)03d quote types.' % vars()
Python has 002 quote types.
>>>
In this case no * specifiers may occur in a format (since they require
a sequential parameter list).
Additional string operations are defined in standard module `string'
and in built-in module `regex'.
---------- Footnotes ----------
(1) A tuple object in this case should be a singleton.
(2) These numbers are fairly arbitrary. They are intended to avoid
printing endless strings of meaningless digits without hampering
correct use and without having to know the exact precision of floating
point values on a particular machine.
File: pylibi, Node: Mutable Sequence Types, Prev: More String Operations, Up: Sequence Types
Mutable Sequence Types
......................
List objects support additional operations that allow in-place
modification of the object. These operations would be supported by
other mutable sequence types (when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created. The following operations are defined on
mutable sequence types (where X is an arbitrary object):
*Operation*
*Result* -- *Notes*
`S[I] = X'
item I of S is replaced by X
`S[I:J] = T'
slice of S from I to J is replaced by T
`del S[I:J]'
same as `S[I:J] = []'
`S.append(X)'
same as `S[len(S):len(S)] = [X]'
`S.count(X)'
return number of I's for which `S[I] == X'
`S.index(X)'
return smallest I such that `S[I] == X' -- (1)
`S.insert(I, X)'
same as `S[I:I] = [X]' if `I >= 0'
`S.remove(X)'
same as `del S[S.index(X)]' -- (1)
`S.reverse()'
reverses the items of S in place
`S.sort()'
permutes the items of S to satisfy `S[I] <= S[J]', for `I < J' --
(2)
Notes:
(1)
Raises an exception when X is not found in S.
(2)
The `sort()' method takes an optional argument specifying a
comparison function of two arguments (list items) which should
return `-1', `0' or `1' depending on whether the first argument is
considered smaller than, equal to, or larger than the second
argument. Note that this slows the sorting process down
considerably; e.g. to sort a list in reverse order it is much
faster to use calls to `sort()' and `reverse()' than to use
`sort()' with a comparison function that reverses the ordering of
the elements.
File: pylibi, Node: Mapping Types, Next: Other Built-in Types, Prev: Sequence Types, Up: Types
Mapping Types
-------------
A "mapping" object maps values of one type (the key type) to arbitrary
objects. Mappings are mutable objects. There is currently only one
standard mapping type, the "dictionary". A dictionary's keys are
almost arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable types
that are compared by value rather than by object identity. Numeric
types used for keys obey the normal rules for numeric comparison: if
two numbers compare equal (e.g. 1 and 1.0) then they can be used
interchangeably to index the same dictionary entry.
Dictionaries are created by placing a comma-separated list of
`KEY:,VALUE' pairs within braces, for example: `{'jack':,4098,
'sjoerd':,4127}' or `{4098:,'jack', 4127:,'sjoerd'}'.
The following operations are defined on mappings (where A is a mapping,
K is a key and X is an arbitrary object):
*Operation*
*Result* -- *Notes*
`len(A)'
the number of items in A
`A[K]'
the item of A with key K -- (1)
`A[K] = X'
set `A[K]' to X
`del A[K]'
remove `A[K]' from A -- (1)
`A.items()'
a copy of A's list of (key, item) pairs -- (2)
`A.keys()'
a copy of A's list of keys -- (2)
`A.values()'
a copy of A's list of values -- (2)
`A.has_key(K)'
`1' if A has a key K, else `0'
Notes:
(1)
Raises an exception if K is not in the map.
(2)
Keys and values are listed in random order.
File: pylibi, Node: Other Built-in Types, Next: Special Attributes, Prev: Mapping Types, Up: Types
Other Built-in Types
--------------------
The interpreter supports several other kinds of objects. Most of these
support only one or two operations.
* Menu:
* Modules::
* Classes and Instances::
* Functions::
* Methods::
* Code Objects::
* Type Objects::
* The Null Object::
* File Objects::
* Internal Objects::
File: pylibi, Node: Modules, Next: Classes and Instances, Prev: Other Built-in Types, Up: Other Built-in Types
Modules
.......
The only special operation on a module is attribute access: `M.NAME',
where M is a module and NAME accesses a name defined in M's symbol
table. Module attributes can be assigned to. (Note that the `import'
statement is not, strictly spoken, an operation on a module object;
`import FOO' does not require a module object named FOO to exist,
rather it requires an (external) *definition* for a module named FOO
somewhere.)
A special member of every module is `__dict__'. This is the dictionary
containing the module's symbol table. Modifying this dictionary will
actually change the module's symbol table, but direct assignment to the
`__dict__' attribute is not possible (i.e., you can write
`M.__dict__['a'] = 1', which defines `M.a' to be `1', but you can't
write `M.__dict__ = {}'.
Modules are written like this: `<module 'sys'>'.
File: pylibi, Node: Classes and Instances, Next: Functions, Prev: Modules, Up: Other Built-in Types
Classes and Class Instances
...........................
(See Chapters 3 and 7 of the Python Reference Manual for these.)
File: pylibi, Node: Functions, Next: Methods, Prev: Classes and Instances, Up: Other Built-in Types
Functions
.........
Function objects are created by function definitions. The only
operation on a function object is to call it: `FUNC(ARGUMENT-LIST)'.
There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the different
object types.
The implementation adds two special read-only attributes: `F.func_code'
is a function's "code object" (see below) and `F.func_globals' is the
dictionary used as the function's global name space (this is the same
as `M.__dict__' where M is the module in which the function F was
defined).
File: pylibi, Node: Methods, Next: Code Objects, Prev: Functions, Up: Other Built-in Types
Methods
.......
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as `append()' on lists)
and class instance methods. Built-in methods are described with the
types that support them.
The implementation adds two special read-only attributes to class
instance methods: `M.im_self' is the object whose method this is, and
`M.im_func' is the function implementing the method. Calling `M(ARG-1,
ARG-2, ..., ARG-N)' is completely equivalent to calling
`M.im_func(M.im_self, ARG-1, ARG-2, ..., ARG-N)'.
(See the Python Reference Manual for more info.)
File: pylibi, Node: Code Objects, Next: Type Objects, Prev: Methods, Up: Other Built-in Types
Code Objects
............
Code objects are used by the implementation to represent
"pseudo-compiled" executable Python code such as a function body. They
differ from function objects because they don't contain a reference to
their global execution environment. Code objects are returned by the
built-in `compile()' function and can be extracted from function
objects through their `func_code' attribute.
A code object can be executed or evaluated by passing it (instead of a
source string) to the `exec' statement or the built-in `eval()'
function.
(See the Python Reference Manual for more info.)
File: pylibi, Node: Type Objects, Next: The Null Object, Prev: Code Objects, Up: Other Built-in Types
Type Objects
............
Type objects represent the various object types. An object's type is
accessed by the built-in function `type()'. There are no special
operations on types. The standard module `types' defines names for all
standard built-in types.
Types are written like this: `<type 'int'>'.
File: pylibi, Node: The Null Object, Next: File Objects, Prev: Type Objects, Up: Other Built-in Types
The Null Object
...............
This object is returned by functions that don't explicitly return a
value. It supports no special operations. There is exactly one null
object, named `None' (a built-in name).
It is written as `None'.
File: pylibi, Node: File Objects, Next: Internal Objects, Prev: The Null Object, Up: Other Built-in Types
File Objects
............
File objects are implemented using C's `stdio' package and can be
created with the built-in function `open()' described under Built-in
Functions below. They are also returned by some other built-in
functions and methods, e.g. `posix.popen()' and `posix.fdopen()' and
the `makefile()' method of socket objects.
When a file operation fails for an I/O-related reason, the exception
`IOError' is raised. This includes situations where the operation is
not defined for some reason, like `seek()' on a tty device or writing a
file opened for reading.
Files have the following methods:
- Method on file: close ()
Close the file. A closed file cannot be read or written anymore.
- Method on file: flush ()
Flush the internal buffer, like `stdio''s `fflush()'.
- Method on file: isatty ()
Return `1' if the file is connected to a tty(-like) device, else
`0'.
- Method on file: read ([SIZE])
Read at most SIZE bytes from the file (less if the read hits EOF
or no more data is immediately available on a pipe, tty or similar
device). If the SIZE argument is negative or omitted, read all
data until EOF is reached. The bytes are returned as a string
object. An empty string is returned when EOF is encountered
immediately. (For certain files, like ttys, it makes sense to
continue reading after an EOF is hit.)
- Method on file: readline ([SIZE])
Read one entire line from the file. A trailing newline character
is kept in the string(1) (but may be absent when a file ends with
an incomplete line). If the SIZE argument is present and
non-negative, it is a maximum byte count (including the trailing
newline) and an incomplete line may be returned. An empty string
is returned when EOF is hit immediately. Note: unlike `stdio''s
`fgets()', the returned string contains null characters (`'\0'')
if they occurred in the input.
- Method on file: readlines ()
Read until EOF using `readline()' and return a list containing the
lines thus read.
- Method on file: seek (OFFSET, WHENCE)
Set the file's current position, like `stdio''s `fseek()'. The
WHENCE argument is optional and defaults to `0' (absolute file
positioning); other values are `1' (seek relative to the current
position) and `2' (seek relative to the file's end). There is no
return value.
- Method on file: tell ()
Return the file's current position, like `stdio''s `ftell()'.
- Method on file: truncate ([SIZE])
Truncate the file's size. If the optional size argument present,
the file is truncated to (at most) that size. The size defaults
to the current position. Availability of this function depends on
the operating system version (e.g., not all UNIX versions support
this operation).
- Method on file: write (STR)
Write a string to the file. There is no return value. Note: due
to buffering, the string may not actually show up in the file until
the `flush()' or `close()' method is called.
- Method on file: writelines (LIST)
Write a list of strings to the file. There is no return value.
(The name is intended to match `readlines'; `writelines' does not
add line separators.)
---------- Footnotes ----------
(1) The advantage of leaving the newline on is that an empty string
can be returned to mean EOF without being ambiguous. Another advantage
is that (in cases where it might matter, e.g. if you want to make an
exact copy of a file while scanning its lines) you can tell whether the
last line of a file ended in a newline or not (yes this happens!).
File: pylibi, Node: Internal Objects, Prev: File Objects, Up: Other Built-in Types
Internal Objects
................
(See the Python Reference Manual for these.)
File: pylibi, Node: Special Attributes, Prev: Other Built-in Types, Up: Types
Special Attributes
------------------
The implementation adds a few special read-only attributes to several
object types, where they are relevant:
* `X.__dict__' is a dictionary of some sort used to store an
object's (writable) attributes;
* `X.__methods__' lists the methods of many built-in object types,
e.g., `[].__methods__' yields `['append', 'count', 'index',
'insert', 'remove', 'reverse', 'sort']';
* `X.__members__' lists data attributes;
* `X.__class__' is the class to which a class instance belongs;
* `X.__bases__' is the tuple of base classes of a class object.
File: pylibi, Node: Exceptions, Next: Built-in Functions, Prev: Types, Up: Built-in Objects
Built-in Exceptions
===================
Exceptions are string objects. Two distinct string objects with the
same value are different exceptions. This is done to force programmers
to use exception names rather than their string value when specifying
exception handlers. The string value of all built-in exceptions is
their name, but this is not a requirement for user-defined exceptions
or exceptions defined by library modules.
The following exceptions can be generated by the interpreter or
built-in functions. Except where mentioned, they have an `associated
value' indicating the detailed cause of the error. This may be a
string or a tuple containing several items of information (e.g., an
error code and a string explaining the code).
User code can raise built-in exceptions. This can be used to test an
exception handler or to report an error condition `just like' the
situation in which the interpreter raises the same exception; but
beware that there is nothing to prevent user code from raising an
inappropriate error.
- built-in exception: AttributeError
Raised when an attribute reference or assignment fails. (When an
object does not support attribute references or attribute
assignments at all, `TypeError' is raised.)
- built-in exception: EOFError
Raised when one of the built-in functions (`input()' or
`raw_input()') hits an end-of-file condition (EOF) without reading
any data. (N.B.: the `read()' and `readline()' methods of file
objects return an empty string when they hit EOF.) No associated
value.
- built-in exception: IOError
Raised when an I/O operation (such as a `print' statement, the
built-in `open()' function or a method of a file object) fails for
an I/O-related reason, e.g., `file not found', `disk full'.
- built-in exception: ImportError
Raised when an `import' statement fails to find the module
definition or when a `from ... import' fails to find a name that
is to be imported.
- built-in exception: IndexError
Raised when a sequence subscript is out of range. (Slice indices
are silently truncated to fall in the allowed range; if an index
is not a plain integer, `TypeError' is raised.)
- built-in exception: KeyError
Raised when a mapping (dictionary) key is not found in the set of
existing keys.
- built-in exception: KeyboardInterrupt
Raised when the user hits the interrupt key (normally `Control-C'
or DEL). During execution, a check for interrupts is made
regularly. Interrupts typed when a built-in function `input()' or
`raw_input()') is waiting for input also raise this exception. No
associated value.
- built-in exception: MemoryError
Raised when an operation runs out of memory but the situation may
still be rescued (by deleting some objects). The associated value
is a string indicating what kind of (internal) operation ran out
of memory. Note that because of the underlying memory management
architecture (C's `malloc()' function), the interpreter may not
always be able to completely recover from this situation; it
nevertheless raises an exception so that a stack traceback can be
printed, in case a run-away program was the cause.
- built-in exception: NameError
Raised when a local or global name is not found. This applies only
to unqualified names. The associated value is the name that could
not be found.
- built-in exception: OverflowError
Raised when the result of an arithmetic operation is too large to
be represented. This cannot occur for long integers (which would
rather raise `MemoryError' than give up). Because of the lack of
standardization of floating point exception handling in C, most
floating point operations also aren't checked. For plain integers,
all operations that can overflow are checked except left shift,
where typical applications prefer to drop bits than raise an
exception.
- built-in exception: RuntimeError
Raised when an error is detected that doesn't fall in any of the
other categories. The associated value is a string indicating what
precisely went wrong. (This exception is a relic from a previous
version of the interpreter; it is not used any more except by some
extension modules that haven't been converted to define their own
exceptions yet.)
- built-in exception: SyntaxError
Raised when the parser encounters a syntax error. This may occur
in an `import' statement, in an `exec' statement, in a call to the
built-in function `eval()' or `input()', or when reading the
initial script or standard input (also interactively).
- built-in exception: SystemError
Raised when the interpreter finds an internal error, but the
situation does not look so serious to cause it to abandon all hope.
The associated value is a string indicating what went wrong (in
low-level terms).
You should report this to the author or maintainer of your Python
interpreter. Be sure to report the version string of the Python
interpreter (`sys.version'; it is also printed at the start of an
interactive Python session), the exact error message (the
exception's associated value) and if possible the source of the
program that triggered the error.
- built-in exception: SystemExit
This exception is raised by the `sys.exit()' function. When it is
not handled, the Python interpreter exits; no stack traceback is
printed. If the associated value is a plain integer, it specifies
the system exit status (passed to C's `exit()' function); if it is
`None', the exit status is zero; if it has another type (such as a
string), the object's value is printed and the exit status is one.
A call to `sys.exit' is translated into an exception so that
clean-up handlers (`finally' clauses of `try' statements) can be
executed, and so that a debugger can execute a script without
running the risk of losing control. The `posix._exit()' function
can be used if it is absolutely positively necessary to exit
immediately (e.g., after a `fork()' in the child process).
- built-in exception: TypeError
Raised when a built-in operation or function is applied to an
object of inappropriate type. The associated value is a string
giving details about the type mismatch.
- built-in exception: ValueError
Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value, and the
situation is not described by a more precise exception such as
`IndexError'.
- built-in exception: ZeroDivisionError
Raised when the second argument of a division or modulo operation
is zero. The associated value is a string indicating the type of
the operands and the operation.