After writing my post on why Python 3 exists which included an explanation about the most common question/complaint about why Python 3 forced textual and binary data into separate types, I heard from people about the second most common question/complaint about Python 3: why did we make
Who can do what?
In its most basic form,
print A is the equivalent of
sys.stdout.write(str(A) + '\n'). If you pass extra arguments separated by commas then they will also be passed to
str() and be printed with a space between each argument. For example,
print A, B, C is equivalent to
sys.stdout.write(' '.join(map(str, [A, B, C])) + '\n'). If there is a trailing comma then the added newline is left off, e.g.
print A, is the same as
Introduced in Python 2.0, the
print >> output, A is the same as
output.write(str(A) + '\n').
The equivalent definition of the
import sys def print(*objects, sep=None, end=None, file=None, flush=False): """A Python translation of the C code for builtins.print(). """ if sep is None: sep = ' ' if end is None: end = '\n' if file is None: file = sys.stdout file.write(sep.join(map(str, objects)) + end) if flush: file.flush()
As you may have noticed, all the features of the
print A, B, C==
print(A, B, C)
print >> output, A==
The obvious thing the
It's all about flexibility
But the real key to the
# Manually ... print A, '...' # For a reusable solution (which also works with a functional print) ... def ellipsis_print(*args): for arg in args: print arg, '', print '...'
But for Python 3, you have much better solutions:
# Manually ... print(A, end='...\n') # Multiple reusable solutions that won't work with a syntactic print... ellipsis_print = lambda *args, **kwargs: print(*args, **kwargs, end='...\n') # Or ... import functools ellipsis_print = functools.partial(print, end='...\n')
In other words, with
builtins.print while you can't do that with a statement.
The flexibility that the Python development team gains is being unshackled from having to make the features of
It should also be mentioned that as a general guideline, syntax is reserved for things that are either impossible to do otherwise or there is a clear readability benefit to the syntax. In the case of
print A and
print(A) is negligible and thus there is no loss in readability. And since we were able to completely replace