[Python-Dev] Replacement for print in Python 3.0 (original) (raw)
Steven Bethard steven.bethard at gmail.com
Fri Sep 2 16:46:58 CEST 2005
- Previous message: [Python-Dev] Replacement for print in Python 3.0
- Next message: [Python-Dev] Replacement for print in Python 3.0
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Charles Cazabon wrote:
Fredrik Lundh <fredrik at pythonware.com> wrote: > next use case: > > print 'foo:', foo, 'bar:', bar, 'baz:', baz, > if frobble > 0: > print 'frobble', frobble > else: > print 'no frobble today'
The need to print /and/ not add a newline isn't nearly as common. print() could take a keyword parameter to skip the newline, or ... print('foo:', foo, 'bar:', bar, 'baz:', baz, frobble and 'frobble: ' + frobble or 'no frobble today') Or the user can just use stdout.write and have full control.
Or you can easily refactor your code to do the print in one line:
if frobble > 0:
frobble_str = 'frobble: ' + frobble
else:
frobble_str = 'no frobble today'
print('foo:', foo, 'bar:', bar, 'baz:', baz, frobble_str)
or similarly:
if frobble > 0:
rest = ['frobble', frobble]
else:
rest = ['no frobble today']
print('foo:', foo, 'bar:', bar, 'baz:', baz, *rest)
I don't know which refactoring you'd prefer, but there are at least a few options here. In the first one you have to be careful to add the extra space yourself. In the second one, you have to know how *args work. But I would claim that the extra mental burden of manually adding a space or understanding *args is about equivalent to the current mental burden of print's trailing-comma behavior.
I also find it more obvious in both refactored examples that the print produces exactly one line.
Of course, there are examples that don't refactor so easily. Here's one:
for i, obj in enumerate(objs):
# do stuff
print i, obj,
# do more stuff
print
If the "do stuff" and "do more stuff" sections are empty, you can write it as something like:
print(*[item for tup in enumerate(objs) for item in tup])
But it's clearly not as beginner-friendly, requiring knowledge of *args and list comprehensions. OTOH, I'd claim that if you need such exacting format, you're not doing beginner stuff anyway. But YMMV.
STeVe
You can wordify anything if you just verb it. --- Bucky Katt, Get Fuzzy
- Previous message: [Python-Dev] Replacement for print in Python 3.0
- Next message: [Python-Dev] Replacement for print in Python 3.0
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]