print , (was Re: Python vs. Perl, which is better to learn?)

Alex Martelli aleax at aleax.it
Fri May 3 03:25:07 EDT 2002


Aahz wrote:
        ...
> <blink>  Learn something new every frickin' day.  I was not familiar with
> this extra cute magic behavior of "print ," at the end of a line.  I

It's called the "softspace" behavior, because that's the name of the
attribute of the file or file-like object that print uses to control it.  
It's best viewed by having a filelike object that traces setting and
getting of softspace, and printing to it -- e.g.:

class Flo(object):
    def __init__(self):
        self._softspace = 0
    def setSS(self, v):
        print "sSS %s->%s"%(self._softspace,v)
        self._softspace = v
    def getSS(self):
        print "gSS ->%s"%self._softspace
        return self._softspace
    softspace=property(getSS,setSS)
    def write(self, buf):
        print "wri %r"%buf
 
flo = Flo()
print >> flo, 'One','Two'
print
print >> flo, 'With a nl\n',
print
print >> flo, 'without',
print
print >> flo, 'finis'

The trace will then be:

gSS ->0
sSS 0->1
wri 'One'
gSS ->1
sSS 1->1
wri ' '
wri 'Two'
wri '\n'
gSS ->1
sSS 1->0
 
gSS ->0
sSS 0->1
wri 'With a nl\n'
gSS ->1
sSS 1->0
 
gSS ->0
sSS 0->1
wri 'without'
 
gSS ->1
sSS 1->1
wri ' '
wri 'finis'
wri '\n'
gSS ->1
sSS 1->0


I think this is pretty instructive.  You'll see the extra ' ' is written
separately, conditionally on the previous value of softspace; SS
itself is set to 1 or 0 depending on whether a \n was last emitted,
etc.  This bit of extra state is kept per-file in the most natural
way, i.e. through a fileobject attribute (if you write your own
fileobjects, make sure their softspace attribute can be set and
read -- care is only needed if you have __slots__ or for a C-coded
extension).

All in all, a neat hack, even though I fully understand not wanting
to rely on such stuff for "production code", when sys.stdout.write
is far simpler and easier to control.  So, I'll agree that my use of
the "print someline," idiom/trick was inferior, in as much as that
short program WAS meant to be an example of "production code"!
'print' is often NOT "the simplest thing that can possibly work"...


Alex




More information about the Python-list mailing list