|
|
|
|
Python Pocket Reference, 2nd EditionBy Mark Lutz2nd Edition November 2001 0-59600-001-8, Order Number: 0018 128 pages, $11.95 |
Sample Excerpt
Specific StatementsThe following sections describe all Python statements. Each section lists the statement's syntax formats, followed by usage details. For compound statements, each appearance of a suite in a statement format stands for one or more other statements, possibly indented as a block under a header line. A suite must be indented under a header if it contains another compound statement (
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 xwhile x: x = x -1if x < 42: print xAssignment
target = expression
target1 = target2 = expression
target1, target2 = expression1, expression2
target1, target2,... = same-length-sequence
(target1, target2,...) = same-length-sequence
[target1, target2,...] = same-length-sequence
Stores references to objects in targets. Expressions yield objects. Targets may be simple names (
X), qualified attributes (X.attr), or indexes and slices (X[i],X[i:j]).The second format assigns expression object to each target. The third format pairs targets with expressions, left to right. The last three formats assign components of any sequence to corresponding targets, from left to right. The sequence on the right must be the same length, but can be any type.
Augmented assignment
As of Python 2.0, a set of additional assignment statement formats, listed in Table 13, are available. Known as "augmented assignment," these formats imply a binary expression plus an assignment. For instance, the following two formats are roughly equivalent:
X = X + YX += Ybut the reference to target
Xneeds to be evaluated only once, and in-place operations may be applied for mutables as an optimization (e.g.,list1+=list2automatically callslist1.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 formatX//=Y(floor division) is new in 2.2.
Table 13: Augmented assignment statements (continued) X += Y
X &= Y
X -= Y
X |= Y
X *= Y
X ^= Y
X /= Y
X »= Y
X %= Y
X «= Y
X **= Y
X //= Y
Expressions
expression
function([value, name=value, ...])
object.method([value, name=value, ...])
Any expression can appear as a statement (but statements cannot appear as expressions). Expressions are commonly used for running functions and for interactive-mode printing.
In function and method calls, actual arguments are separated by commas and are normally matched to arguments in function
defheaders by position. Calls may optionally list specific argument names in functions to receive passed values, by using the name=value keyword syntax.apply( )-like call syntax
As of Python 2.0, special syntax can be used in function and method call argument lists to achieve the same effect as an
apply( )built-in function call. If args and kw are a tuple and a dictionary, respectively, the following are equivalent:apply(f, args, kw)f(*args, **kw)Both formats call function
fwith positional arguments args and keyword arguments kw. The latter format is intended to be symmetric with function header arbitrary-argument syntax such asdeff(*args,**kw):.The print Statement
print [value [, value]* [,]]
print >> fileobj [, value [, value]* [,]]
Displays the printable representation of values on stdout stream (the current setting of
sys.stdout). Adds spaces between values. Trailing comma suppresses linefeed normally added at end of list. Becausewritemethod of the object currently referenced bysys.stdout, the following is equivalent toX:import syssys.stdout.write(str(X) + '\n')To redirect
sys.stdoutto any object with awritemethod:sys.stdout = open('log', 'a') # any object with a write( )print "Warning-bad spam!" # goes to the object's write( )Extended print form
As of Python 2.0, the
sys.stdout):fileobj = open('log', 'a')print >> fileobj, "Warning-bad spam!"If the file object is
None,sys.stdoutis used. Becausesys.stdoutcan be reassigned, the>>form is not strictly needed; however, it can often avoid both explicitwritemethod calls and saving and restoring the originalsys.stdoutvalue around a redirectedThe if Statement
if test: suite [elif test: suite]* [else: suite]Selects from among one or more actions (statement blocks). Runs suite associated with first
iforeliftest that is true, orelsesuite if all are false.The while Statement
while test: suite [else: suite]General loops. Keeps running first suite while test at top is true. Runs
elsesuite if loop exits without hitting abreakstatement.The for Statement
for target in sequence: suite [else: suite]Sequence iteration. Assigns items in sequence to target and runs first suite for each. Runs
elsesuite if loop exits without hitting abreakstatement. target may be anything that can appear on the left side of an "=" assignment statement (e.g.,for(x,y)intuplelist:).In 2.2, works by first trying to obtain an iterator object with
iter(sequence)and then calling that object'snext( )method repeatedly untilStopIterationis raised (see "The yield Statement"). In earlier versions, or if no iterator object can be obtained (e.g., no__iter__method is defined), works instead by repeatedly indexing sequence at successively higher offsets until anIndexErroris raised.The pass Statement
passDo-nothing placeholder statement, when syntactically necessary.
The break Statement
breakImmediately exits closest enclosing
whileorforloop statement, skipping its associatedelse(if any).The continue Statement
continueImmediately goes to the top of the closest enclosing
whileorforloop statement; resume in the loop header line.The del Statement
del name del name[i] del name[i:j] del name.attributeDeletes names, items, slices, and attributes. Removes bindings.
The exec Statement
exec codestring [in globaldict [, localdict]]Compiles and runs code strings. codestring is any Python statement as a string; run in namespace containing the
exec, or the global/local namespace dictionaries if specified (localdict defaults to globaldict). codestring can also be a compiled code object. Also seecompile,eval, andexecfilein the section "Built-in Functions."The def Statement
def name([arg, arg=value,... *arg, **arg]): suiteMakes new functions. Creates a function object and assigns it to variable name. Each call to a function object generates a new, local scope, where assigned names are local to the function call by default (unless declared global). See also the section "Namespace and Scope Rules" later in the book. Arguments are passed by assignment; in a
defheader, they may be defined by any of the formats in Table 14.
Table 14: Argument definition formats Argument format
Interpretation
arg
Simple name, matched by name or position
arg=value
Default value if
argnot passed*arg
Collects extra positional
args**arg
Collects extra keyword
args passed by nameMutable default argument values are evaluated once at
defstatement time, not on each call, so may retain state between calls (but classes are better state-retention tools):>>> def grow(a, b=[]):... b.append(a)... print b...>>> grow(1); grow(2)[1][1, 2]lambda expressions
Functions may also be created with the
lambdaexpression form:lambdaarg,arg,...:expression. Inlambda, arg is as indef, expression is the implied return value, and the generated function is simply returned as thelambdaresult to be called later, instead of being assigned to a variable. Becauselambdais an expression, not a statement, it may be used in places that adefcannot be (e.g., within an argument list of a call).The return Statement
return [expression]Exits the enclosing function and returns expression value as the result of the call to the function. Hint: return a tuple for multiple-value function results.
The yield Statement
yield expressionOptional in 2.2; enable with
from__future__importgenerators. Suspend function state and return expression. On the next iteration, the function's prior state is restored, and control resumes immediately after theyieldstatement. Use areturnstatement with no value to end the iteration, or simply fall off the end of the function:def generate_ints(N):for i in xrange(N):yield iGenerators and iterators
In 2.2, functions containing a
yieldstatement are compiled as generators; when called, they return a generator object that supports the iterator interface (i.e., anext( )method).Iterators are objects returned by the
iter(X)built-in function; they define anext( )method, which returns the next item in the iteration or raises aStopIterationexception to end the iteration. Classes may provide an__iter__method to overload theiter(X)built-in function call; if defined, the result is used to step through objects inforloops, rather than the traditional__getitem__indexing overload scheme.The global Statement
global name [, name]*Namespace declaration: inside a class or function, treats appearances of name as references to a global (module-level) variable by that name--whether it is assigned or not. Because of Python scope rules, you need to declare only global names that are assigned within a
def(global references are automatically found in the enclosing module).The import Statement
import module [, module]* import [package.]* module [, [package.]* module]* import module as nameModule access: imports a module as a whole. Modules contain names fetched by qualification (e.g., module.attribute).
modulenames the target module--a Python file or compiled module located in a directory insys.path(PYTHONPATH), without its filename suffix (e.g., omit the ".py"). Assignments at the top level of a Python file create module object attributes. Theasclause assigns a variable name to the imported module object; useful to provide shorter synonyms for long module names.Import operations compile a file's source to byte-code if needed (and save it in a .pyc file if possible), then execute the compiled code from top to bottom to generate module object attributes by assignment. Use the
reloadbuilt-in function to force recompilation and execution of already-loaded modules; see also__import__used byimport, in the later section "Built-in Functions."In the Jython implementation, imports may also name Java class libraries; Jython generates a Python module wrapper that interfaces with the Java library. In Standard (C) Python, imports may also load compiled C and C++ extensions.
Package imports
If used, package prefix names give enclosing directory names, and module dotted paths reflect directory hierarchies. An import of the form
importdir1.dir2.modloads the file at directory pathdir1/dir2/mod.py, wheredir1must be contained by a directory listed on PYTHONPATH. Each directory through which an import descends must have a (possibly empty)__init__.pyfile that serves as the directory level's module namespace. All names assigned in__init__.pyfiles become attributes of the directory's module object. Directory packages can resolve conflicts caused by the linear nature of PYTHONPATH.The from Statement
from [package.]* module import name [, name]* from [package.]* module import * from module import name as othernameModule names access: import (copy) variable names out of a module and use them later without enclosing module name qualification. The
frommodimport* format copies all names assigned at the top level of the module, except names with a single leading underscore or names not listed in the module's__all__list-of-strings attribute (if defined).If used, the
asclause creates a name synonym. If used, package import paths work the same as inimportstatements (e.g.,fromdir1.dir2.modimportX), but the package path needs to be listed only in thefromitself. Due to new scoping rules, the "*" format generates warnings in 2.2 if it appears nested in a function or class.The
fromstatement is also used to enable future (but still experimental) language additions, withfrom__future__importfeaturename. This format must appear only at the top of a module file (preceded only by an optional doc string).The class Statement
class name [( super [, super]* )]: suiteMakes new class objects, which are factories for instance objects. Builds a new class object and assigns it to variable name. The
classstatement introduces a new local name scope, and all names assigned in theclassstatement generate class object attributes shared by all instances of the class. Important class features include the following (see also the later sections "Object-Oriented Programming" and "Operator Overloading Methods"):
- Superclasses from which the new class inherits attributes are listed in parentheses in the header (e.g.,
classSub(Super1,Super2):).
- Assignments in the suite generate class attributes inherited by instances: nested
defstatements make methods, assignment statements make simple class members, etc.
- Calling the class generates instance objects. Each instance object has its own attributes and inherits the attributes of the class and all of its superclasses.
- Specially named method definitions overload operations.
The try Statement
try: suite [except [name [, data]]: suite]* [else: suite] try: suite finally: suiteCatches exceptions.
trystatements may specifyexceptclauses with suites that serve as handlers for exceptions raised during thetrysuite,elseclauses that run if no exception occurs during thetrysuite, andfinallyclauses that run whether an exception happens or not.Exceptions may be raised by Python, or explicitly (see also the
raisestatement). Inexceptclauses, an extra variable name (data) can be used to intercept an extra data item raised with the exception name. Table 15 lists all the clauses that may appear in atrystatement.finallycannot be mixed withexceptorelse.
Table 15: try statement clause formats Clause format
Interpretation
except:
Catch all (other) exceptions
except name:
Catch a specific exception only
except name, value:
Catch exception and extra data
except (name1, name2):
Catch any of the exceptions
else:
Run if no exceptions raised
finally:
Always run on the way out
Common variations include:
exceptclassname, X:- Catch a class exception, and assign
Xto the raised instance.
except (name1,name2,name2),X:- Catch any of the exceptions, and assign X to the extra data.
The raise Statement
raisestring- Matches
exceptthat names same string object.
raisestring,data- Passes extra data object with exception (default is
None); assigned to variableXin anexceptstring,X:trystatement clause.
raiseinstance- Same as
raiseinstance.__class__,instance.
raiseclass,instance- Matches
exceptthat names this class, or any of its superclasses. Passes the class instance object as extra data with exception, to be assigned to X in anexceptclass,X:trystatement clause.
raise- Re-raises the current exception.
Triggers exceptions. Control jumps to the matching
exceptclause of the most recently entered matchingtrystatement, or to the top level of process (where it ends the program and prints a standard error message). May use to raise built-in or user-defined exceptions. Without arguments, re-raises the most recent exception. See also "Built-in Exceptions" for exceptions raised by Python.Class exceptions
Exceptions may be string objects (first two formats) or class instances (second two formats).
trystatementexceptclauses that name string objects are matched by string identity (is), not by value (==).trystatementexceptclauses that name classes catch an instance of that class, as well as any of its subclasses. All built-in exceptions are now class objects.Class exceptions support exception categories, which may be easily extended. Because
trystatements catch all subclasses when they name a superclass, exception categories may be modified by altering the set of subclasses without breaking existingtrystatements. The raised instance object also provides storage for extra information about the exception:class General:def __init__(self, x):self.data = xclass Specific1(General): passclass Specific2(General): passtry:raise Specific1('spam')except General, X:print X.data # prints 'spam'For backward compatibility with prior Python releases that only supported string exceptions, these
raiseformats are also allowed:raise class [, arg]raise class, (arg, arg,...)These are the same as the instance format
raiseclass([arg...]). The first format occurs when arg is not an instance of class. Python generates and raises an instance automatically, even if theraiselists only a class name (i.e.,raiseClass is the same asraiseClass( )). It is suggested but not required that user-defined exceptions inherit from the built-in exception classException(see the section "Built-in Exceptions").The assert Statement
assert expression [, message]Debugging checks. If expression is false, raises
AssertionError, passing message as an extra data item if specified. The-Ocommand-line flag removes assertion logic.
Back to: Python Pocket Reference, 2nd Edition
© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com