By Mark Lutz
Cover | Table of Contents
[]*| bconstant widthpython [option*] [ scriptfilename | -c command | - ] [arg*]
-d-i-O-OO-O, but also removes docstrings from
byte-code.
[]*| bconstant widthpython [option*] [ scriptfilename | -c command | - ] [arg*]
-d-i-O-OO-O, but also removes docstrings from
byte-code.
-S-t-tt
issues error instead).
-u-U'xxx' treated like
u'xxx' (highly experimental in 2.1.1).
-v-x#!cmd.
-h-V-W argarg is
action:message:category:module:lineno.
See warnings module documentation, new in 2.1, in
the Python Library Reference (http://www.python.org/doc/).
sys.argv[0].
-c commandsys.argv[0] is set to -c.
-*sys.argv[1:]).
sys.path.
sys.prefix,
sys.exec_prefix). The default module search path
uses sys.prefix/lib.
-d option.-i option.-O option.-u option.-v option.|
Operators
|
Description
|
|---|---|
lambda args: expr |
Anonymous function maker
|
X or Y |
Logical OR: Y is evaluated only if X is false
|
X and Y |
Logical AND: Y is evaluated only if X is true
|
not X |
Logical negation
|
X < Y, X <= Y, X > Y, X >= Y, X == Y, X <> Y, X != Y, X is Y, X is not Y, X in S, X not in S |
Comparison operators, equality operators,
inequality operators, object identity tests, sequence membership
|
X | Y |
Bitwise OR
|
X ^ Y |
Bitwise exclusive OR
|
X & Y |
Bitwise AND
|
X << Y, X >> Y |
Shift X left, right by Y bits
|
X + Y, X—Y |
Addition/concatenation, subtraction
|
X * Y, X % Y, X / Y, X // Y |
Multiply/repetition, remainder/format, division, floor division
|
-X, +X, ~X, X**Y |
Unary negation, identity, bitwise complement, power
|
X[i], X[i:j], X.attr, X(...) |
Indexing, slicing, attribute references, function calls
|
(...), [...], {...}, `...`
|
Tuple, list, dictionary,
conversion to string
|
None is false.
and and or operators
stop as soon as a result is known (short-circuit) and return one of
the two operand objects (on left or right).
|
Operator
|
Description
|
|---|---|
X < Y |
Strictly less than
|
X <= Y |
Less than or equal
|
X > Y |
Strictly greater than
|
X >= Y |
Greater than or equal
|
X == Y |
Equal (same value)
|
X != Y |
Not equal (same as
X<
>Y)
|
X is Y |
Same object
|
X is not Y |
Negated object identity
|
X < Y < Z |
Chained comparisons |
1234, -24, 099999999L, 42l1.23, 3.14e-10, 4E210, 4.0e+2100177, 0x9ff3+4j, 3.0+4.0j, 3J/ and //).
"Python's", 'Python"s'"""This is a multiline block"""'Python\'s\n''\n' is a byte with binary value 012).
"This" "is" "concatenated"r'a raw\string', R'another\one'r'c:\dir1\file').
u"..."if, while,
for, raise, calls, etc.).
\, an
unclosed ( ), [], or
{} pair, or an unclosed, triple-quoted string.
Multiple simple statements can appear on a line if separated with a
semicolon (;).
# (not in a string constant)
and span to the end of the line.
_ _doc_ _
attribute. See the pydoc module and script in the
Python Library Reference for automated extraction and display tools.
_), followed by any number of letters, digits, or
underscores.
@,
$, or ? in its syntax, though
they may appear in string constants and comments.
if, while,
etc.); otherwise, it can appear on the same line as the statement
header. The following are both valid constructs:
if x < 42:
print x
while x: x = x -1
if x < 42: print x
X), qualified
attributes (X.attr), or indexes and slices
(X[i], X[i:j]).
X = X + Y X += Y
X needs to be
evaluated only once, and in-place operations may be applied for
mutables as an optimization (e.g., list1
+= list2 automatically calls
list1.extend(list2), instead of the slower
concatenation operation implied by +). Classes may
overload in-place assignments with method names that begin with an
"i" (e.g., _ _iadd_ _ for
+=, _ _add_ _ for
+). The format X
//= Y (floor division) is new
in 2.2.
X, in
object.X) are known as attributes and live in
object namespaces. Assignments in some lexical scopes initialize object
namespaces (modules, classes).
Assignment: object.X = valueX in the
namespace of the object being qualified.
Reference: object.XX in the
object, then all accessible classes above it (for
instances and classes). This is the definition of
inheritance.
X) involve lexical scope rules.
Assignments bind such names to the local scope, unless they are
declared global.
Assignment: X = valueX local: creates or changes name
X in the current local scope by default. If
X is declared global, creates or changes name
X in the enclosing module's scope. Local
variables are stored in the call stack for quick access.
Reference: XX in at most
three scopes: the current local scope
(function), then the current global scope
(module), then the built-in scope
(module _ _builtin_ _). Local
and global scope contexts are defined in Table 1-16.
X in the
current local scope (function), then in the local scopes of all
lexically enclosing functions (if any, from inner to outer), then in
the current global scope (module), then in the built-in scope
(module _ _builtin_ _). Global
declarations make the search begin in the global scope instead.
|
Code context
|
Global scope
|
Local scope
|
|---|---|---|
|
Module
|
Same as local
|
The module itself
|
|
Function, method
|
Enclosing module
|
Function call
|
|
Class
|
Enclosing module
|
class statement |
|
Script, interactive mode
|
Same as local
|
module _ _main_ _ |
class statement creates a
class object and assigns it to a name.
class statements create class
attributes, which export object state and
behavior.
defs, with special first arguments to receive the
instance.
self.X
= V) in methods create per-instance
attributes.
object.attribute, if object is
a class or instance.
_X), and those not listed on the module's
_ _all_ _ list, are not copied over when a client
uses from module
import *. This is not strict
privacy, though, as such names can still be accessed apart from the
from..* statement.
class statements with two leading underscores only
(e.g., _ _X) are mangled at compile time to
include the enclosing class name as a prefix (e.g., _ _getitem_ _, and
X is an instance of this class, then the
expression X[i] is equivalent to the method call
X._ _getitem_ _(i).
_ _add_ _ method need not perform an addition (or
concatenation). Moreover, classes generally may mix numeric and
collection methods and mutable and nonmutable operations.
_ _init_ _(self [, arg]*)class(args...). Constructor: initializes the
new instance, self.
_ _del_ _(self)_ _repr_ _(self)`self`, repr(self),
print self (if no _
_str_ _). Returns string representation.
_ _str_ _(self)str(self), print
self (or uses _ _repr_ _ if
defined). Returns string representation.
_ _cmp_ _(self, other), _ _rcmp_ _self >
x, x ==
self, cmp(self,
x), etc. Called for all comparisons for which no
more specific method (such as _ _lt_ _) is defined
or inherited (see rich comparison methods below). Returns -1, 0, or 1
for self less than, equal to, or greater than
other. If no rich comparison or _ _cmp_
_ methods are defined, class instances compare by their
identity (address in memory). Note: _ _rcmp_ _
right-side method is no longer supported as of Release 2.1.
_ _hash_ _(self)dictionary[self],
hash(self). Returns a unique and unchanging
integer hash-key.
_ _call_ _(self [, arg]*)self(args...), when instance is called like a
function.
_ _getattr_ _(self, name)self.name, when name is an
undefined attribute access (not called if name
exists in or is inherited by _
_builtin_ _ module. Because this scope is always searched
last on name lookups, these functions are always available in
programs without imports. However, their names are not reserved words
and may be hidden by assignments to the same name in global or local
scopes.
abs(N)N.apply(func, args [, keys])func (a function,
method, class, etc.), passing the positional arguments in tuple
args, and the keyword arguments in dictionary
keys. Returns func call result.
buffer(object [, offset [, size]])object (see the Python Library Reference).
callable(object)object is callable; else, returns 0.chr(Int)Int.
cmp(X, Y)X < Y),
(X == Y), or
(X > Y),
respectively.
coerce(X, Y)X and Y converted to a common
type.
compile(string, filename, kind)string into a code object.
string is a Python string containing Python
program code. filename is a string used in error
messages (and is usually the name of the file from which the code was
read, or <string> if typed interactively).
kind can be exec if
string contains statements;
eval if string is an
expression; or single, which prints the output of
an expression statement that evaluates to something other than
None. The resulting code object can be executed
with exec statements or eval
calls.
complex(real [, imag])J or j suffix:
real+imagJ).
imag defaults to 0.
delattr(object, name)name (a string) from
object. Similar to del
obj.name, but name is a string,
not a variable (e.g., delattr(a,'b') is like
del a.b).
dir([object])exceptions; this module never needs to be imported
explicitly, because the exception names are provided in the built-in
scope namespace. Most built-in exceptions have an associated extra
data value with details.
ExceptionStandardErrorSystemExit; subclass of the
Exception root class.
ArithmeticError OverflowError,
ZeroDivisionError,
FloatingPointError; subclass of
StandardError.
LookupErrorIndexError,
KeyError; subclass of
StandardError.
EnvironmentErrorIOError, OSError); subclass of
StandardError. New in Release 1.5.2.
AssertionErrorassert statement's test is false.AttributeErrorEOFErrorinput( ) or
raw_input( ).
FloatingPointErrorIOErrorImportErrorIndexErrorKeyErrorKeyboardInterruptMemoryErrorNameErrorNotImplementedErrorOSErroros module error (its
os.error exception). New in 1.5.2.
OverflowErrorRuntimeErrorX._ _dict_ _X's writable
attributes.
I._ _methods_ _I's methods (name
strings); available on many built-in types.
I._ _members_ _I's data attributes
(name strings); available on many built-in types.
I._ _class_ _I was generated.
In 2.2, this also applies to object types; most objects will have a
_ _class_ _ attribute (e.g., []._ _class_
_ == list ==
type([])).
C._ _bases_ _C's base classes, as listed
in C's class statement header.
X._ _name_ _X's name as a string; for classes,
the name in the statement header; for modules, the name as used in
imports, or "_ _main_ _" for the module at the top
level of a program (e.g., the main file run to launch a program).
import module, and qualify
module names (module.name)
from module
import name, and use module
names unqualified (name)
from module
import *, and use module names
unqualified (name)
argv in the
sys module, either use import
sys and name sys.argv, or use
from sys
import argv and name
argv.
sys module contains interpreter-related
exports. It also provides access to some environment components, such
as the command line, standard streams, and so on.
argv[command,
arguments...]. Like C's
argv array.
byteorderbig for
big-endian). New in 2.0.
builtin_module_namescopyrightdllhandledisplayhook(func)sys.displayhook to a one-argument function to
customize output.
_ _displayhook_ _displayhook (for restores).excepthook(type, value, traceback)sys.excepthook to a three-argument function to
customize exception displays.
_ _excepthook_ _excepthook (for restores).exc_info( )(type, value,
traceback). Specific to current thread. Subsumes
exc_type, exc_value, and
exc_traceback in Python 1.5 and later.
exc_typeexc_valueraise). Not thread-specific.
exc_tracebackexec_prefixexecutableexit([N])N (default
0) by raising SystemExit built-in exception (can
be caught in a try statement and ignored). See
also the string module defines constants and variables
for processing string objects, above and beyond string type
operations. See also string built-in type operations and
string-related built-in functions in Section 1.6, and Section 1.19.
string module function call such as
func(str, arg) is generally now
also accessible as str.func(arg). Where
appropriate, both call formats are listed.
string
module is available as object methods, but not all; constants and
some module functions are still available only in the
string module. Function entries with just one
listed call signature are not available as string methods. Similarly,
some string methods are not available in this module (see the string
type in Section 1.6).
digits'0123456789'.hexdigits'0123456789abcdefABCDEF'.letterslowercase and
uppercase.
lowercase'abcdefghijklmnopqrstuvwxyz'.
octdigits'01234567'.printabledigits, letters,
punctuation, and whitespace.
punctuationuppercase'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.whitespacestring.whitespace).
atof(s)s to floating-point. Like built-in
float( ) function.
atoi(s [, base])s to integer of given
base (default is 10). Like built-in int(
) function.
atol(s [, base])s to Python long integer
(unlimited precision) of given base (default is
10). Like built-in os module is the primary operating system (OS)
services interface. It provides generic operating-system support and
a standard, platform-independent OS interface. The
os module includes tools for environments,
processes, files, shell commands, and much more. It also includes a
nested submodule, os.path, that provides a
portable interface to directory processing tools.
os and os.path
for systems programming are generally portable across most Python
platforms. However, some os exports are not
available on all platforms (e.g., fork is
available on Unix but not Windows). Because the portability of such
calls changes over time, consult the Python Library Reference for
platform details.
erroros.error and built-in
OSError exception. Raised for
os module-related errors. The accompanying value
is a pair containing the numeric error code from
errno and the corresponding string, as would be
printed by the C function perror( ). See the
module errno in the Python Library Reference for
names of the error codes defined by the underlying OS.
errno, the value of the C errno
variable; and strerror, the corresponding error
message from strerror( ). For exceptions that
involve a file pathname (e.g., chdir( ),
unlink( )), the exception instance also contains
the attribute filename, the filename passed in.
nameos (e.g., "posix",
"nt", "dos", "mac",
"os2", "ce", "java"). See also
sys.platform in Section 1.16.
pathos.path.split is a platform-independent directory
name tool that internally uses an appropriate platform-specific call.
re module is the standard regular
expression-matching interface (new in 1.5). Regular expression (RE)
patterns are specified as strings. This module must be
imported.
compile(pattern [, flags])pattern string into a regular
expression object, for later matching. flags
(combinable by bitwise | operator):
I or IGNORECASE or (?i)L or LOCALE or (?L)\w, \W,
\b, \B, \s,
\S, \d, and
\D dependent on the current 8-bit locale (default
is 7-bit U.S. ASCII).
M or MULTILINE or (?m)S or DOTALL or (?s)U or UNICODE or (?u)\w, \W,
\b, \B, \s,
\S, \d, and
\D dependent on Unicode character properties (new
in 2.0).
X or VERBOSE or (?x)match(pattern, string [, flags])string
match the pattern string, returns a corresponding
MatchObject instance, or None if no match.
flags as in compile.
search(pattern, string [, flags])string for a location matching
pattern; returns a corresponding MatchObject
instance, or None if no match.
flags as in compile.
split(pattern, string [, maxsplit=0])string by occurrences of
pattern. If capturing ( ) are
used in pattern, occurrences of patterns or
subpatterns are also returned.
sub(pattern, repl, string [, count=0])pattern (a string or
an RE object) in string by
repl. repl can be a string or a
function called with a single MatchObject argument, which must return
the replacement string. repl may also include
sequence escapes \1, \2, etc.
to use substrings that matched groups, or \0 for
all.
subn(pattern, repl, string [, count=0])sub, but returns a tuple:
(new-string,
number-of-subs-made).
findall(pattern, string)pattern in string. If one or
more groups are present in the pattern, returns a list of groups. New
in 1.5.2.
anydbmpickle (and cPickle)shelveanydbm
files.
shelve module implements persistent object
stores. shelve in turn uses the
pickle module to convert (serialize) in-memory
Python objects to byte-stream strings and the
anydbm module to store serialized byte-stream
strings in access-by-key files. See also Section 1.25 later in the book (not part of
the standard library).
anydbm module selects the
keyed-access file implementation in your Python interpreter and
presents a dictionary-like API for scripts. A persistent object
shelve is used like a simple anydbm file, except that the
anydbm module is replaced by
shelve, and the stored value
can be almost any kind of Python object (but keys are still strings).
import shelveimport anydbmdbm, gbmd,
bsddb... whatever is installed.
file = shelve.open('filename')file = anydbm.open('filename', 'c')dbm file.file['key1'] = value'key1'.value = file['key2']'key2' entry.count = len(file)index = file.keys( )for).
found = file.has_key('key3')'key3'.del file['key4']'key4'.file.close( )dbm files and shelves work like dictionaries that
must be opened before use; all mapping operations and some dictionary
methods work.
dbm files and shelves, can also pass
mode ('r',
'w', etc.) and protection
(access-mode) parameters to open if desired (some DBM flavors require
extra arguments).
Button, Frame),
options are keyword arguments (e.g.,
text="press"), and
composition is object embedding, not pathnames
(e.g., Label(Top,...)).
from Tkinter import * # widgets, constants
def msg( ): # callback handler
print 'hello stdout...'
top = Frame( ) # make a container
top.pack( )
Label(top, text="Hello world").pack(side=TOP)
widget = Button(top, text="press", command=msg)
widget.pack(side=BOTTOM)
top.mainloop( )