gratuitous new features in 2.0

Guido van Rossum guido at beopen.com
Sat Aug 26 10:38:46 EDT 2000


"John W. Baxter" <jwbnews at scandaroon.com> writes:
> Guido is so darn sharp that it's easy to agree which his 
> positions...particularly after he's had a give and take with other darn 
> sharp folks and taken their good ideas into account.

Thanks! ;-)  Please take the following idea into account:

Suppose you have written a function that uses the print statement:

    def table(n):
	for j in range(1, n+1):
	    for i in range(1, n+1):
		print i, 'x', j, '=', i*j
	    print

Now you are asked to make it print to another file -- a standard
example of how software typically is asked to evolve.

The new print syntax makes this a straightforward change:

    import sys

    def table(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

Without the new print syntax, you'd first have to transform your
function from usint print to using write(), and then use a default
argument:

    import sys

    def table(n, file=sys.stdout):
	for j in range(1, n+1):
	    for i in range(1, n+1):
		file.write("%d * %d = %d\n" % (i, j, i*j))
	    file.write("\n")

That's more work, and in order to be able to that you need to learn
how to change from print to write(), and string formatting using %.
The alternative using assignment to sys.stdout looks bad too:

    import sys

    def table(n, file=sys.stdout):
	save = sys.stdout
	try:
	    sys.stdout = file
	    for j in range(1, n+1):
		for i in range(1, n+1):
		    print i, 'x', j, '=', i*j
		print
	finally:
	    sys.stdout = save

I'm not saying that you should always do it this way.  Both
transformations have their place.  But I believe that in the course of
learning to program, using the extended print statement poses fewer
stumbling blocks.

It's possible that for Python 3000 we decide to deprecate print in
favor of a write() function.  But for Python 2.0, there's no
deprecating print just doesn't seem to be the right thing to do.

--Guido van Rossum (home page: http://www.pythonlabs.com/~guido/)



More information about the Python-list mailing list