This repository has been archived by the owner on Oct 27, 2019. It is now read-only.
forked from python/peps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pep-0214.txt
390 lines (293 loc) · 13 KB
/
pep-0214.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
PEP: 214
Title: Extended Print Statement
Version: $Revision$
Last-Modified: $Date$
Author: [email protected] (Barry Warsaw)
Status: Final
Type: Standards Track
Content-Type: text/x-rst
Created: 24-Jul-2000
Python-Version: 2.0
Post-History: 16-Aug-2000
Introduction
============
This PEP describes a syntax to extend the standard 'print'
statement so that it can be used to print to any file-like object,
instead of the default ``sys.stdout``. This PEP tracks the status and
ownership of this feature. It contains a description of the
feature and outlines changes necessary to support the feature.
This PEP summarizes discussions held in mailing list forums, and
provides URLs for further information, where appropriate. The CVS
revision history of this file contains the definitive historical
record.
Proposal
========
This proposal introduces a syntax extension to the print
statement, which allows the programmer to optionally specify the
output file target. An example usage is as follows::
print >> mylogfile, 'this message goes to my log file'
Formally, the syntax of the extended print statement is::
print_stmt: ... | '>>' test [ (',' test)+ [','] ] )
where the ellipsis indicates the original print_stmt syntax
unchanged. In the extended form, the expression just after >>
must yield an object with a ``write()`` method (i.e. a file-like
object). Thus these two statements are equivalent::
print 'hello world'
print >> sys.stdout, 'hello world'
As are these two statements::
print
print >> sys.stdout
These two statements are syntax errors::
print ,
print >> sys.stdout,
Justification
=============
'print' is a Python keyword and introduces the print statement as
described in section 6.6 of the language reference manual [1]_.
The print statement has a number of features:
- it auto-converts the items to strings
- it inserts spaces between items automatically
- it appends a newline unless the statement ends in a comma
The formatting that the print statement performs is limited; for
more control over the output, a combination of ``sys.stdout.write()``,
and string interpolation can be used.
The print statement by definition outputs to ``sys.stdout``. More
specifically, ``sys.stdout`` must be a file-like object with a ``write()``
method, but it can be rebound to redirect output to files other
than specifically standard output. A typical idiom is::
save_stdout = sys.stdout
try:
sys.stdout = mylogfile
print 'this message goes to my log file'
finally:
sys.stdout = save_stdout
The problem with this approach is that the binding is global, and
so affects every statement inside the try: clause. For example,
if we added a call to a function that actually did want to print
to stdout, this output too would get redirected to the logfile.
This approach is also very inconvenient for interleaving prints to
various output streams, and complicates coding in the face of
legitimate try/except or try/finally clauses.
Reference Implementation
========================
A reference implementation, in the form of a patch against the
Python 2.0 source tree, is available on SourceForge's patch
manager [2]_. This approach adds two new opcodes, ``PRINT_ITEM_TO`` and
``PRINT_NEWLINE_TO``, which simply pop the file like object off the
top of the stack and use it instead of ``sys.stdout`` as the output
stream.
(This reference implementation has been adopted in Python 2.0.)
Alternative Approaches
======================
An alternative to this syntax change has been proposed (originally
by Moshe Zadka) which requires no syntax changes to Python. A
``writeln()`` function could be provided (possibly as a builtin), that
would act much like extended print, with a few additional
features::
def writeln(*args, **kws):
import sys
file = sys.stdout
sep = ' '
end = '\n'
if kws.has_key('file'):
file = kws['file']
del kws['file']
if kws.has_key('nl'):
if not kws['nl']:
end = ' '
del kws['nl']
if kws.has_key('sep'):
sep = kws['sep']
del kws['sep']
if kws:
raise TypeError('unexpected keywords')
file.write(sep.join(map(str, args)) + end)
``writeln()`` takes a three optional keyword arguments. In the
context of this proposal, the relevant argument is 'file' which
can be set to a file-like object with a ``write()`` method. Thus::
print >> mylogfile, 'this goes to my log file'
would be written as::
writeln('this goes to my log file', file=mylogfile)
``writeln()`` has the additional functionality that the keyword
argument 'nl' is a flag specifying whether to append a newline or
not, and an argument 'sep' which specifies the separator to output
in between each item.
More Justification by the BDFL
==============================
The proposal has been challenged on the newsgroup. One series of
challenges doesn't like '>>' and would rather see some other
symbol.
* Challenge: Why not one of these?
::
print in stderr items,....
print + stderr items,.......
print[stderr] items,.....
print to stderr items,.....
Response: If we want to use a special symbol (``print <symbol>``
expression), the Python parser requires that it is not already a
symbol that can start an expression -- otherwise it can't decide
which form of print statement is used. (The Python parser is a
simple LL(1) or recursive descent parser.)
This means that we can't use the "keyword only in context trick"
that was used for "import as", because an identifier can start an
expression. This rules out +stderr, \[sterr\], and to stderr. It
leaves us with binary operator symbols and other miscellaneous
symbols that are currently illegal here, such as 'import'.
If I had to choose between 'print in file' and 'print >> file' I
would definitely choose '>>'. In part because 'in' would be a new
invention (I know of no other language that uses it, while '>>' is
used in sh, awk, Perl, and C++), in part because '>>', being
non-alphabetic, stands out more so is more likely to catch the
reader's attention.
* Challenge: Why does there have to be a comma between the file and
the rest?
Response: The comma separating the file from the following expression is
necessary! Of course you want the file to be an arbitrary
expression, not just a single word. (You definitely want to be
able to write ``print >>sys.stderr``.) Without the expression the
parser would't be able to distinguish where that expression ends
and where the next one begins, e.g.
::
print >>i +1, 2
print >>a [1], 2
print >>f (1), 2
* Challenge: Why do you need a syntax extension? Why not
writeln(file, item, ...)?
Response: First of all, this is lacking a feature of the print
statement: the trailing comma to print which suppresses the final
newline. Note that 'print a,' still isn't equivalent to
'sys.stdout.write(a)' -- print inserts a space between items, and
takes arbitrary objects as arguments; ``write()`` doesn't insert a
space and requires a single string.
When you are considering an extension for the print statement,
it's not right to add a function or method that adds a new feature
in one dimension (where the output goes) but takes away in another
dimension (spaces between items, and the choice of trailing
newline or not). We could add a whole slew of methods or
functions to deal with the various cases but that seems to add
more confusion than necessary, and would only make sense if we
were to deprecate the print statement altogether.
I feel that this debate is really about whether print should have
been a function or method rather than a statement. If you are in
the function camp, of course adding special syntax to the existing
print statement is not something you like. I suspect the
objection to the new syntax comes mostly from people who already
think that the print statement was a bad idea. Am I right?
About 10 years ago I debated with myself whether to make the most
basic from of output a function or a statement; basically I was
trying to decide between "print(item, ...)" and "print item, ...".
I chose to make it a statement because printing needs to be taught
very early on, and is very important in the programs that
beginners write. Also, because ABC, which lead the way for so
many things, made it a statement. In a move that's typical for
the interaction between ABC and Python, I changed the name from
WRITE to print, and reversed the convention for adding newlines
from requiring extra syntax to add a newline (ABC used trailing
slashes to indicate newlines) to requiring extra syntax (the
trailing comma) to suppress the newline. I kept the feature that
items are separated by whitespace on output.
Full example: in ABC,
::
WRITE 1
WRITE 2/
has the same effect as::
print 1,
print 2
has in Python, outputting in effect "1 2\n".
I'm not 100% sure that the choice for a statement was right (ABC
had the compelling reason that it used statement syntax for
anything with side effects, but Python doesn't have this
convention), but I'm also not convinced that it's wrong. I
certainly like the economy of the print statement. (I'm a rabid
Lisp-hater -- syntax-wise, not semantics-wise! -- and excessive
parentheses in syntax annoy me. Don't ever write ``return(i) or
if(x==y):`` in your Python code! :-)
Anyway, I'm not ready to deprecate the print statement, and over
the years we've had many requests for an option to specify the
file.
* Challenge: Why not > instead of >>?
Response: To DOS and Unix users, >> suggests "append", while >
suggests "overwrite"; the semantics are closest to append. Also,
for C++ programmers, >> and << are I/O operators.
* Challenge: But in C++, >> is input and << is output!
Response: doesn't matter; C++ clearly took it from Unix and
reversed the arrows. The important thing is that for output, the
arrow points to the file.
* Challenge: Surely you can design a ``println()`` function can do all
what ``print>>file`` can do; why isn't that enough?
Response: I think of this in terms of a simple programming
exercise. Suppose a beginning programmer is asked to write a
function that prints the tables of multiplication. A reasonable
solution is::
def tables(n):
for j in range(1, n+1):
for i in range(1, n+1):
print i, 'x', j, '=', i*j
print
Now suppose the second exercise is to add printing to a different
file. With the new syntax, the programmer only needs to learn one
new thing: ``print >> file``, and the answer can be like this::
def tables(n, file=sys.stdout):
for j in range(1, n+1):
for i in range(1, n+1):
print >> file, i, 'x', j, '=', i*j
print >> file
With only a print statement and a ``println()`` function, the
programmer first has to learn about ``println()``, transforming the
original program to using ``println()``::
def tables(n):
for j in range(1, n+1):
for i in range(1, n+1):
println(i, 'x', j, '=', i*j)
println()
and **then** about the file keyword argument::
def tables(n, file=sys.stdout):
for j in range(1, n+1):
for i in range(1, n+1):
println(i, 'x', j, '=', i*j, file=sys.stdout)
println(file=sys.stdout)
Thus, the transformation path is longer::
(1) print
(2) print >> file
vs.
::
(1) print
(2) println()
(3) println(file=...)
Note: defaulting the file argument to ``sys.stdout`` at compile time
is wrong, because it doesn't work right when the caller assigns to
``sys.stdout`` and then uses ``tables()`` without specifying the file.
This is a common problem (and would occur with a ``println()``
function too). The standard solution so far has been::
def tables(n, file=None):
if file is None:
file = sys.stdout
for j in range(1, n+1):
for i in range(1, n+1):
print >> file, i, 'x', j, '=', i*j
print >> file
I've added a feature to the implementation (which I would also
recommend to ``println()``) whereby if the file argument is ``None``,
``sys.stdout`` is automatically used. Thus,
::
print >> None, foo bar
(or, of course, ``print >> x`` where x is a variable whose value is
None) means the same as
::
print foo, bar
and the ``tables()`` function can be written as follows::
def tables(n, file=None):
for j in range(1, n+1):
for i in range(1, n+1):
print >> file, i, 'x', j, '=', i*j
print >> file
.. XXX this needs more justification, and a section of its own
References
==========
.. [1] http://docs.python.org/reference/simple_stmts.html#print
.. [2] http://sourceforge.net/patch/download.php?id=100970
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil
End: