281
Comment:
|
7644
Comment on iterator related 'magic'
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
This page discusses the benefits of replacing the current print statement with an equivalent builtin. The output function presented below does everything the print statement does without requiring an hacking of the grammar, and also makes a number of things significantly easier. | This page discusses the benefits of replacing the current `print` statement with an equivalent builtin. The `write` and `writeln` functions presented below do everything the `print` statement does without requiring any hacking of the grammar, and also make a number of things significantly easier. Guido has made it clear he wants to get rid of the `print` statement in ["Python3.0"]. This page considers why we would want to go that way, and how we can actually get there. It will probably be turned into a PEP at some point. === Benefits of using a function instead of a statement === * Extended call syntax provides better interaction with sequences * Keyword argument `sep` allows item separator to be changed easily and obviously * Keyword argument `linesep` could optionally allow line separator to be changed easily and obviously * Keyword argument `stream` allows easy and obvious redirection * The builtin can be replaced for application wide customisation (e.g. per-thread logging) * Interacts well with PEP 309's partial function application, and the rest of Python's ability to handle functions === Getting there from here === The example implementation below shows that creating a function with the desired behaviour is quite straightforward. However, calling the builtin `print` is a problem due to the fact that `print` is a reserved word in Python 2.x. Since the `print` statement will be around until Py3K allows us to break backwards compatibility, devising a transition plan that lets programmers 'get ready early' for the Py3K transition becomes a significant challenge. If, on the other hand, the builtin has a different name, it is quite feasible to introduce it during the 2.x series. In [http://www.python.org/peps/pep-3000.htm PEP 3000], it is suggested that the `print` statement be replaced by two builtins: `write` and `writeln`. These names are used in the example below. By using alternative names, and providing the builtins in the 2.x series, it is possible to 'future-proof' code against the removal of the `print` statement in Py3k. This technique of having two printing operations is not uncommon - Java has both `print` and `println` methods, and C# has `Write` and `WriteLine`. The main problem with the approach is that the `writeln` form will actually be more commonly used, but has the longer, less obvious name of the two proposed functions. This perception of relative use is based on a comparison of relative usage levels of the two current forms of the `print` statement (i.e., with and without the trailing comma) by some of the developers on python-dev. Some other names for the builtins which have been suggested are: * `print` - excellent name, but causes transition problems as described above * `println` - avoids the transition problems, reflects default behaviour of adding a line, matches Java method name * `printline` - alternative to `println`, that avoids the somewhat cryptic abbreviation * `writeline` - alternative to `writeln` that avoids the somewhat cryptic abbreviation * `out` - not a verb, and converting to it may be problematic due to shadowing by variable names * `output` - nice symmetry with input, but using the term as a verb is not typical === Sample implementation === This is a Python 2.4 compatible sample implementation. This version of `writeln` doesn't provide a `linesep` keyword argument in order to keep things simple. {{{#!python def write(*args, **kwds): """Functional replacement for the print statement This function does NOT automatically append a line separator (use writeln for that) """ # Nothing to do if no positional arguments if not args: return # Parse the keyword-only optional arguments kwd_values = { "sep": " ", "stream": sys.stdout, } # This code can't use dict.update directly, since it needs # to ignore the keyword arg if the value is set to None for name, default in kwd_values.items(): try: value = kwds[name] except KeyError: continue del kwds[name] if item is not None: kwd_values[name] = value if kwds: raise TypeError("write() and writeln() only accept sep and stream as keyword arguments") sep, stream = kwd_values["sep"], kwd_values["stream"] # Perform the print operation without building the whole string stream.write(str(args[0])) for arg in args[1:]: stream.write(sep) stream.write(str(arg)) def writeln(*args, **kwds): """Functional replacement for the print statement >>> writeln(1, 2, 3) 1 2 3 >>> writeln(1, 2, 3, sep='') 123 >>> writeln(1, 2, 3, sep=', ') 1, 2, 3 >>> import sys >>> writeln(1, 2, 3, stream=sys.stderr) 1 2 3 >>> writeln(*range(10)) 0 1 2 3 4 5 6 7 8 9 >>> writeln(*(x*x for x in range(10))) 0 1 4 9 16 25 36 49 64 81 """ # Perform the print operation without building the whole string write(*args, **kwds) write("\n", **kwds) }}} === Code comparisons === These are some comparisons of current `print` statements with the equivalent code using the builtins `write` and `writeln`. {{{#!python # Standard printing print 1, 2, 3 writeln(1, 2, 3) # Printing without any spaces print "%d%d%d" % (1, 2, 3) writeln(1, 2, 3, sep='') # Print as comma separated list print "%d, %d, %d" % (1, 2, 3) writeln(1, 2, 3, sep=', ') # Print without a trailing newline print 1, 2, 3, write(1, 2, 3) # Print to a different stream print >> sys.stderr, 1, 2, 3 writeln(1, 2, 3, stream=sys.stderr) # Print a simple sequence print " ".join(map(str, range(10))) writeln(*range(10)) # Print a generator expression print " ".join(str(x*x) for x in range(10)) writeln(*(x*x for x in range(10))) }}} === Newline / No-newline === Another possibility to deal with the newline / no-newline cases would be to have a single function which would take an extra keyword argument "linesep" or "end" (or perhaps some slight magic: an empty string as the last argument), so to print without newline, you would do {{{#!python # Print without a trailing newline print 1, 2, 3, writeln(1, 2, 3, end='') # or (shorthand) writeln(1, 2, 3, '') }}} The default case should be to insert a newline. === Iterating Iterables === Another potentially interesting improvement could be for the function to iterate all iterables, in order to be able to use generator expressions without having to use the star syntax and to avoid the creation of a temporary sequence. This would allow: {{{#!python # Print a generator expression print " ".join(str(x*x) for x in range(10)) writeln(x*x for x in range(10)) # Or optionally writeln((x*x for x in range(10)), iter=1) }}} This behaviour could be optionally triggered by a keyword argument "iter". Another possibility would be to always do the iteration and to force the caller to str() the generator if he wants to print it without iteration (happens rarely). Nailing down this kind of behaviour is trickier than one might think. The python-dev discussion of the Python 2.5 candidate library function [http://mail.python.org/pipermail/python-dev/2005-March/052215.html itertools.walk] goes over some of the potential problems. We've survived without fancy iterator handling in the print statement - let's avoid adding anything we don't have a demonstrated need for (the extended call syntax stuff comes 'for free' with the conversion to using a function). - ''Nick Coghlan'' |
This page discusses the benefits of replacing the current print statement with an equivalent builtin. The write and writeln functions presented below do everything the print statement does without requiring any hacking of the grammar, and also make a number of things significantly easier.
Guido has made it clear he wants to get rid of the print statement in ["Python3.0"]. This page considers why we would want to go that way, and how we can actually get there. It will probably be turned into a PEP at some point.
Benefits of using a function instead of a statement
- Extended call syntax provides better interaction with sequences
Keyword argument sep allows item separator to be changed easily and obviously
Keyword argument linesep could optionally allow line separator to be changed easily and obviously
Keyword argument stream allows easy and obvious redirection
- The builtin can be replaced for application wide customisation (e.g. per-thread logging)
- Interacts well with PEP 309's partial function application, and the rest of Python's ability to handle functions
Getting there from here
The example implementation below shows that creating a function with the desired behaviour is quite straightforward. However, calling the builtin print is a problem due to the fact that print is a reserved word in Python 2.x. Since the print statement will be around until Py3K allows us to break backwards compatibility, devising a transition plan that lets programmers 'get ready early' for the Py3K transition becomes a significant challenge.
If, on the other hand, the builtin has a different name, it is quite feasible to introduce it during the 2.x series. In [http://www.python.org/peps/pep-3000.htm PEP 3000], it is suggested that the print statement be replaced by two builtins: write and writeln. These names are used in the example below. By using alternative names, and providing the builtins in the 2.x series, it is possible to 'future-proof' code against the removal of the print statement in Py3k.
This technique of having two printing operations is not uncommon - Java has both print and println methods, and C# has Write and WriteLine. The main problem with the approach is that the writeln form will actually be more commonly used, but has the longer, less obvious name of the two proposed functions. This perception of relative use is based on a comparison of relative usage levels of the two current forms of the print statement (i.e., with and without the trailing comma) by some of the developers on python-dev.
Some other names for the builtins which have been suggested are:
print - excellent name, but causes transition problems as described above
println - avoids the transition problems, reflects default behaviour of adding a line, matches Java method name
printline - alternative to println, that avoids the somewhat cryptic abbreviation
writeline - alternative to writeln that avoids the somewhat cryptic abbreviation
out - not a verb, and converting to it may be problematic due to shadowing by variable names
output - nice symmetry with input, but using the term as a verb is not typical
Sample implementation
This is a Python 2.4 compatible sample implementation. This version of writeln doesn't provide a linesep keyword argument in order to keep things simple.
1 def write(*args, **kwds):
2 """Functional replacement for the print statement
3
4 This function does NOT automatically append a line separator (use writeln for that)
5 """
6 # Nothing to do if no positional arguments
7 if not args:
8 return
9 # Parse the keyword-only optional arguments
10 kwd_values = {
11 "sep": " ",
12 "stream": sys.stdout,
13 }
14 # This code can't use dict.update directly, since it needs
15 # to ignore the keyword arg if the value is set to None
16 for name, default in kwd_values.items():
17 try:
18 value = kwds[name]
19 except KeyError:
20 continue
21 del kwds[name]
22 if item is not None:
23 kwd_values[name] = value
24 if kwds:
25 raise TypeError("write() and writeln() only accept sep and stream as keyword arguments")
26 sep, stream = kwd_values["sep"], kwd_values["stream"]
27 # Perform the print operation without building the whole string
28 stream.write(str(args[0]))
29 for arg in args[1:]:
30 stream.write(sep)
31 stream.write(str(arg))
32
33 def writeln(*args, **kwds):
34 """Functional replacement for the print statement
35
36 >>> writeln(1, 2, 3)
37 1 2 3
38 >>> writeln(1, 2, 3, sep='')
39 123
40 >>> writeln(1, 2, 3, sep=', ')
41 1, 2, 3
42 >>> import sys
43 >>> writeln(1, 2, 3, stream=sys.stderr)
44 1 2 3
45 >>> writeln(*range(10))
46 0 1 2 3 4 5 6 7 8 9
47 >>> writeln(*(x*x for x in range(10)))
48 0 1 4 9 16 25 36 49 64 81
49 """
50 # Perform the print operation without building the whole string
51 write(*args, **kwds)
52 write("\n", **kwds)
Code comparisons
These are some comparisons of current print statements with the equivalent code using the builtins write and writeln.
1 # Standard printing
2 print 1, 2, 3
3 writeln(1, 2, 3)
4
5 # Printing without any spaces
6 print "%d%d%d" % (1, 2, 3)
7 writeln(1, 2, 3, sep='')
8
9 # Print as comma separated list
10 print "%d, %d, %d" % (1, 2, 3)
11 writeln(1, 2, 3, sep=', ')
12
13 # Print without a trailing newline
14 print 1, 2, 3,
15 write(1, 2, 3)
16
17 # Print to a different stream
18 print >> sys.stderr, 1, 2, 3
19 writeln(1, 2, 3, stream=sys.stderr)
20
21 # Print a simple sequence
22 print " ".join(map(str, range(10)))
23 writeln(*range(10))
24
25 # Print a generator expression
26 print " ".join(str(x*x) for x in range(10))
27 writeln(*(x*x for x in range(10)))
Newline / No-newline
Another possibility to deal with the newline / no-newline cases would be to have a single function which would take an extra keyword argument "linesep" or "end" (or perhaps some slight magic: an empty string as the last argument), so to print without newline, you would do
The default case should be to insert a newline.
Iterating Iterables
Another potentially interesting improvement could be for the function to iterate all iterables, in order to be able to use generator expressions without having to use the star syntax and to avoid the creation of a temporary sequence. This would allow:
This behaviour could be optionally triggered by a keyword argument "iter". Another possibility would be to always do the iteration and to force the caller to str() the generator if he wants to print it without iteration (happens rarely).
Nailing down this kind of behaviour is trickier than one might think. The python-dev discussion of the Python 2.5 candidate library function [http://mail.python.org/pipermail/python-dev/2005-March/052215.html itertools.walk] goes over some of the potential problems. We've survived without fancy iterator handling in the print statement - let's avoid adding anything we don't have a demonstrated need for (the extended call syntax stuff comes 'for free' with the conversion to using a function). - Nick Coghlan