
40
|
Python Pocket Reference
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 f with a positional arguments
sequence of
args and a keyword arguments dictionary of kw.
The latter format is intended to be symmetric with function
header arbitrary-argument syntax such as
def f(*args,
**kw):
. It is also more flexible, since it can be more easily
combined with positional and keyword arguments (e.g.,
f(1,2,foo=3,bar=4,*args,**kw)).
The print Statement
print [value [, value]* [,]]
print >> fileobj [, value [,value]* [,]]
print displays the printable representation of values on a
stdout stream (the current setting of sys.stdout) as well as
adds spaces between values. The trailing comma suppresses
the linefeed that is normally added at the end of a list.
Because
print simply calls the write method of the object
currently referenced by
sys.stdout, the following is equiva-
lent to
print X:
import sys
sys.stdout.write(str(X) + '\n')
To redirect print text to files or class objects, reassign sys.
stdout
to any object with a write method:
sys.stdout = open('log', 'a') # any object with a write()
print "Warning-bad spam!" # goes to the object's write()