what's the big deal for print()

steve+comp.lang.python at pearwood.info steve+comp.lang.python at pearwood.info
Sat Jun 25 00:01:43 EDT 2011


John Gordon wrote:

> In <d3558c5d-0fe6-4da7-843d-c2f45b2bf869 at y13g2000yqy.googlegroups.com>
> pipehappy <pipehappy at gmail.com> writes:
> 
>> Why people want print() instead of print str? That's not a big deal
>> and the old choice is more natural. Anyone has some clue?
> 
> Because the new Python uses print().  print "str" is the old way.


I think you missed the point of the question, which is, *why* does the new
Python (version 3+) use a function print() instead of a statement?

The problems with print as a statement includes:

It requires special treatment in the compiler, instead of just being an
ordinary function like len(), etc.

It's hard to come up with special syntax to add extra functionality to print
statement. Compare the ugly syntax needed to add support for printing to
writable files in Python 2:

    print >>fileobj, arg  # what does the mysterious >> syntax mean?

compared to the natural way it works in Python 3:

    print(arg, file=fileobj)

Likewise, changing the delimiter between arguments. Python 3 has:

    >>> print(1, 2, 3, sep="*")
    1*2*3

while Python 2 requires you to generate the string by hand, and then print
it:

    >>> print '*'.join('%s' % x for x in (1, 2, 3))
    1*2*3


One Frequently Asked Question is "How do I get rid of the newline after
printing?" In Python 2, you leave a comma at the end of the print
statement. What? A comma? How does that make *any* sense at all???
Unfortunately, while that gets rid of the newline, it also leaves spaces
between items:

>>> def example():
...     print 1,
...     print 2,
...     print 3
...
>>> example()
1 2 3

Here's the Python 3 version:

>>> def example():
...     print(1, sep='', end='')
...     print(2, sep='', end='')
...     print(3, sep='')
...
>>> example()
123


To get the same result in Python 2, you have to use sys.stdout.write().


The canonical explanation for why print is now a function is here:

http://www.python.org/dev/peps/pep-3105/




-- 
Steven




More information about the Python-list mailing list