By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,616 Members | 1,184 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,616 IT Pros & Developers. It's quick & easy.

Please hear my plea: print without softspace

P: n/a

Why can't we have an additional 'print' statement, that behaves
exactly like 'print' but doesn't insert that damn blank between two
arguments?

Could be called 'printn' or 'prin1' or 'prinn' anything similar you
like.

Would make my life so much easier. Often I start with a nice and short
print statement, then there happen to be more arguments and neat
formatting becomes more important and as a result I find myself
rewriting the code over and over again just to cope with those blanks
I'm forced to take into account.

Coding would be easier: If there are more arguments to print, it's
just the argument list that grows. If you need a blank then add one.
But you don't have to rewrite your arguments into expressions which
can be tedious and isn't efficient anyway if its an extra operation
just to get rid of those blanks.

What do you think?

Martin
Jul 18 '05 #1
Share this Question
Share on Google+
30 Replies


P: n/a
def pprint(*args):
txt = ""
for a in args:
txt += str(a)
print txt

Is it ok?

--
Don't you know why your Python application has crashed?
Take a look to http://www.pycrash.org
--
Posted via Mailgate.ORG Server - http://www.Mailgate.ORG
Jul 18 '05 #2

P: n/a
In article <dc************************************@mygate.mai lgate.org>,
Carmine Noviello <cn*******@hotmail.com> writes
def pprint(*args):
txt = ""
for a in args:
txt += str(a)
print txt

Is it ok?

--
Don't you know why your Python application has crashed?
Take a look to http://www.pycrash.org

Give stdout a good hiding :)

##############
class hidesoftspace:
def __init__(self,fobj):
self.__dict__['_fobj'] = fobj
fobj.softspace = False
def __getattr__(self,a):
if a=='softspace': return False
return getattr(self._fobj,a)
def __setattr__(self,a,v):
if a=='softspace': return
setattr(self._fobj,a,v)

import sys
print 'before hiding',1,2,3,4
sys.stdout=hidesoftspace(sys.stdout)
print 'after hiding',1,2,3,4
##############
results in

before hiding 1 2 3 4
after hiding1234
--
Robin Becker
Jul 18 '05 #3

P: n/a
Martin Bless wrote on Sat, 28 Feb 2004 11:56:55 GMT:
Why can't we have an additional 'print' statement, that behaves
exactly like 'print' but doesn't insert that damn blank between two
arguments?

Could be called 'printn' or 'prin1' or 'prinn' anything similar you
like. <snip> What do you think?


In these cases I tend to use string formatting, e.g.:

print '%s-%s-%s' % (1,2,3)

As others have already pointed out, there are several other ways too, so
making a new keyword for this doesn't seem very useful.

--
Yours,

Andrei

=====
Real contact info (decode with rot13):
ce******@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
Jul 18 '05 #4

P: n/a
In data Sat, 28 Feb 2004 12:01:40 +0000 (UTC), Carmine Noviello ha
scritto:
def pprint(*args):
txt = ""
for a in args:
txt += str(a)
print txt

Is it ok?


I would use this instead:

def pprint(*args):
txt = []
for a in args:
txt.append(a)
print ''.join(txt)

which is a lot faster :)

--
Valentino Volonghi aka Dialtone
Now using Windows for Notebook Hw failure
X Python Newsreader developer
http://sourceforge.net/projects/xpn/
Jul 18 '05 #5

P: n/a
In article <9n****************************@40tude.net>,
Valentino Volonghi aka Dialtone <di**************@virgilio.it> wrote:
In data Sat, 28 Feb 2004 12:01:40 +0000 (UTC), Carmine Noviello ha
scritto:
def pprint(*args):
txt = ""
for a in args:
txt += str(a)
print txt

Is it ok?


I would use this instead:

def pprint(*args):
txt = []
for a in args:
txt.append(a)
print ''.join(txt)

which is a lot faster :)


Sorry.

Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
def pprint(*args): .... txt = []
.... for a in args:
.... txt.append(a)
.... print ''.join(txt)
.... pprint (1,2,3)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in pprint
TypeError: sequence item 0: expected string, int found

def pprint (*args):
print ''.join ([str(x) for x in args])

Regards. Mel.
Jul 18 '05 #6

P: n/a
On Saturday 28 February 2004 07:32 am, Valentino Volonghi aka Dialtone wrote:
In data Sat, 28 Feb 2004 12:01:40 +0000 (UTC), Carmine Noviello ha

scritto:
def pprint(*args):
txt = ""
for a in args:
txt += str(a)
print txt

Is it ok?


I would use this instead:

def pprint(*args):
txt = []
for a in args:
txt.append(a)
print ''.join(txt)

which is a lot faster :)


why not?

def pprint(*args):
print ''.join(args)

if you want it to be more robust you could do

def pprint(*args):
print ''.join(map(str,args))

That would try and convert all the items to a string first before joining
them.

Jul 18 '05 #7

P: n/a
In article <ed**************@jessikat.fsnet.co.uk>, Robin Becker wrote:


##############
class hidesoftspace:
def __init__(self,fobj):
self.__dict__['_fobj'] = fobj
fobj.softspace = False
def __getattr__(self,a):
if a=='softspace': return False
return getattr(self._fobj,a)
def __setattr__(self,a,v):
if a=='softspace': return
setattr(self._fobj,a,v)

import sys
print 'before hiding',1,2,3,4
sys.stdout=hidesoftspace(sys.stdout)
print 'after hiding',1,2,3,4
##############


Would you perhaps care to comment a bit more, or provide a pointer to
some docs? It seems that there is a "softspace" atribute in the
sys.stdout file object, and that this attribute gets set by the print
statement itself. With your clever trick you make it imposible for
someone to set this attribute to anything else but "False". What are
the exact semantics behind this?

I tried this:

import sys
print sys.stdout.softspace
0
print "test:", 1, 2, 3, sys.stdout.softspace
test: 1 2 3 1
print sys.stdout.softspace
0

Which seems to support my explanation, but what exactly are the
semantics of "softspace"?

Thanks
/npat
Jul 18 '05 #8

P: n/a
In data Sat, 28 Feb 2004 09:44:57 -0700, kosh ha scritto:
why not?

def pprint(*args):
print ''.join(args)

if you want it to be more robust you could do

def pprint(*args):
print ''.join(map(str,args))

That would try and convert all the items to a string first before joining
them.


I would have used the list comprehension solution that Mel Wilson posted
but I was in a hurry and wrote wrong code...

Actually I don't like map() and I always try to use LC as much as
possible, I think they are a lot more readable.

--
Valentino Volonghi aka Dialtone
Now using Windows for Notebook Hw failure
X Python Newsreader developer
http://sourceforge.net/projects/xpn/
Jul 18 '05 #9

P: n/a
In article <sl*****************@localhost.localdomain>, Nick Patavalis
<np**@efault.net> writes
In article <ed**************@jessikat.fsnet.co.uk>, Robin Becker wrote:


##############
class hidesoftspace:
def __init__(self,fobj):
self.__dict__['_fobj'] = fobj
fobj.softspace = False
def __getattr__(self,a):
if a=='softspace': return False
return getattr(self._fobj,a)
def __setattr__(self,a,v):
if a=='softspace': return
setattr(self._fobj,a,v)

import sys
print 'before hiding',1,2,3,4
sys.stdout=hidesoftspace(sys.stdout)
print 'after hiding',1,2,3,4
##############


Would you perhaps care to comment a bit more, or provide a pointer to
some docs? It seems that there is a "softspace" atribute in the
sys.stdout file object, and that this attribute gets set by the print
statement itself. With your clever trick you make it imposible for
someone to set this attribute to anything else but "False". What are
the exact semantics behind this?
I tried this:

import sys
print sys.stdout.softspace
0
print "test:", 1, 2, 3, sys.stdout.softspace
test: 1 2 3 1
print sys.stdout.softspace
0

Which seems to support my explanation, but what exactly are the
semantics of "softspace"?

Thanks
/npat


OK I'll try. I believe softspace is a boolean attribute of the standard
file class which is used by print to indicate that a space should be
inserted in the stream before the next item. Logically it should always
be false at the beginning of a print sequence and true after the print
of an item.

You have to be careful testing this as prints at the prompt don't behave
properly ie you always get a linefeed in the command terminal.

try
from sys import stdout
print stdout.softspace,stdout.softspace,;print stdout.softspace

should give

0 1 1

my class just ensures that a wrapped (warped :)) file will never have
its softspace set to true and thus we won't get the extra spaces; in
short print always thinks the wrapped file is at the start of a print
sequence.
-softspaced in the head-ly yrs-
Robin Becker
Jul 18 '05 #10

P: n/a
On Saturday 28 February 2004 10:26 am, Valentino Volonghi aka Dialtone wrote:
In data Sat, 28 Feb 2004 09:44:57 -0700, kosh ha scritto:
why not?

def pprint(*args):
print ''.join(args)

if you want it to be more robust you could do

def pprint(*args):
print ''.join(map(str,args))

That would try and convert all the items to a string first before joining
them.


I would have used the list comprehension solution that Mel Wilson posted
but I was in a hurry and wrote wrong code...

Actually I don't like map() and I always try to use LC as much as
possible, I think they are a lot more readable.


I use map, reduce, filter etc pretty rarely but I think in this case it is a
very simple way to say what I mean there. I just want str called on every
element in args and have a list returned with that result.

I use list comps a lot in other places but things like map do have their
place.

Jul 18 '05 #11

P: n/a
"Carmine Noviello" <cn*******@hotmail.com> writes:
def pprint(*args):
txt = ""
for a in args:
txt += str(a)
print txt

Is it ok?


import sys
def pprint(*args):
for a in args:
sys.stdout.write(a)
Jul 18 '05 #12

P: n/a

"Martin Bless" <mb@muenster.de> wrote in message
news:40**************@news.muenster.de...

Why can't we have an additional 'print' statement, that behaves
exactly like 'print' but doesn't insert that damn blank between two
arguments? .... What do you think?


For exact control of output, use file.write(string).
print is a convenient wrapper for casual output to stdout,
especially with the interactive console.
Or write your own wrapper for custom default formating.

Terry J. Reedy


Jul 18 '05 #13

P: n/a
On Sat, 28 Feb 2004 11:56:55 GMT, mb@muenster.de (Martin Bless)
declaimed the following in comp.lang.python:

Why can't we have an additional 'print' statement, that behaves
exactly like 'print' but doesn't insert that damn blank between two
arguments?
Because we'd then have newbies complaining because they can't
tell different outputs apart when they use the wrong "print" statement
<G>
Would make my life so much easier. Often I start with a nice and short <snip> can be tedious and isn't efficient anyway if its an extra operation
just to get rid of those blanks.

What do you think?
/I/ think "print" should be reserved for quick and simple,
interactive prompting style, I/O operations, and anything that may
require custom, exact, formatting should be performed using
sys.stdout.write() and related... possibly with dedicated
functions/classes/modules (a report writer, say)
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #14

P: n/a
[Andrei <fa**@fake.net>]
In these cases I tend to use string formatting, e.g.:

print '%s-%s-%s' % (1,2,3)

As others have already pointed out, there are several other ways too, so
making a new keyword for this doesn't seem very useful.


That's exactly the point I'm trying to make: I think this new keyword
*would* be extremely useful.

The general advice I received so far is: "roll your own writer object,
create a wrapper, do those string calculations yourself, then hand the
ready to print output to 'print' or some 'write' method. 'print'
isn't good enough for sophisticated use, there are many ways to format
your output correctly..."

I *know* there are many ways. The point is: many of these
"workarounds" only come into play because there *is no* built in
variant of 'print' that doesn't emit blanks.

Advocating the 'print statement':

Let's remember:

print_stmt ::= "print" ( [expression ("," expression)* [","]]
| ">>" expression [("," expression)+ [","]] )

- Obviously it *is* an important language feature: it even has its own
keyword.
- It's easy to use and *scalable* (no parentheses, variable number of
arguments).
- readable: pure list of arguments.
- Its efficient, since it has its built in ways of transforming
expressions to output strings, processing one by one. No need to join
those parts first.
- As a language feature it's well documented.
- 'print statements' stand for themselves and are highly expressive
and self documenting. Understanding, copying and pasting relies less
on context.

In one word: Looks like a very pythonic feature to me. Very
attractive.

And I'd simply like to benefit from all of these advantages. 99% seem
to be ok and because of 1% bad we can't use it to the full.

Aside: And there even must have been a time where 'print' has been
considered important enough to fight a long battle about introducing
the "chevron" form ('>>')...

Don't panic:

Of course I'm not saying we should change the existing behaviour of
'print' in any way.

But:

On the other hand: introducing a new keyword like 'printn' or 'prin0'

- wouldn't break any existing code
- wouldn't introduce a change of language structure
- could be documented within a few sentences ("... behaves like
'print' but does not insert blanks ...")
- and my suspicion is that the implentation in C isn't much of a
problem.

It's just like having a variant of something we allready have with
slightly different semantics. And that's ok and exactly what we want.
And it's no problem because we'd have a unique new name for it.

As far as I can see there's much benefit and little costs.

Ok, then back to where I startet. Let me asked again:

"Can we have an additional 'print' statement, that behaves exactly
like 'print' but doesn't insert blanks between arguments?"

curious,

Martin

Jul 18 '05 #15

P: n/a
mb@muenster.de (Martin Bless) wrote in
news:40**************@news.muenster.de:

[...]
Ok, then back to where I startet. Let me asked again:

"Can we have an additional 'print' statement, that behaves
exactly like 'print' but doesn't insert blanks between
arguments?"


Probably not.

I've wondered, though, whether there couldn't be a different
character instead of a ',' to alter the behavior of print. Maybe a
trailing '+' to indicate that what follows is to concatenate
directly.

And yet I've been able to work around that little annoyance; it's not
that there is no way to format output the way you want.

--
rzed

Jul 18 '05 #16

P: n/a
> I've wondered, though, whether there couldn't be a different
character instead of a ',' to alter the behavior of print. Maybe a
trailing '+' to indicate that what follows is to concatenate
directly.

And yet I've been able to work around that little annoyance; it's not
that there is no way to format output the way you want.

It seems that you are saying:

print "hello ", "world" + #-> "hello world"

That looks like "magic syntax", and should rightfully return a syntax
error, because + already has a meaning for most all data types in
Python. Changing the behavior of print when a syntax error is present,
is the wrong thing to do.

The right thing to do (if it were to happen at all) is to make
fileobject.softspace "sticky" under some condition, perhaps after a call
to fileobject.SetSoftSpace(False) (which doesn't currently exist).

- Josiah
Jul 18 '05 #17

P: n/a
Josiah Carlson wrote:
The right thing to do (if it were to happen at all) is to make
fileobject.softspace "sticky" under some condition, perhaps after a
call to fileobject.SetSoftSpace(False) (which doesn't currently
exist).


The right thing to do is to put make stdout a builtin and deprecate the
print statement. The "smart" behavior of the print statement causes more
trouble than it's worth. I admit that I use the print statement myself
occasionally, but only because 'sys.stdout.write' is too long to type all
the time, and never with more than one argument.
--
Rainer Deyke - ra*****@eldwood.com - http://eldwood.com
Jul 18 '05 #18

P: n/a
On Mon, 01 Mar 2004 21:42:21 GMT, "Rainer Deyke" <ra*****@eldwood.com>
wrote:
Josiah Carlson wrote:
The right thing to do (if it were to happen at all) is to make
fileobject.softspace "sticky" under some condition, perhaps after a
call to fileobject.SetSoftSpace(False) (which doesn't currently
exist).


The right thing to do is to put make stdout a builtin and deprecate the
print statement. The "smart" behavior of the print statement causes more
trouble than it's worth. I admit that I use the print statement myself
occasionally, but only because 'sys.stdout.write' is too long to type all
the time, and never with more than one argument.


IMO, this is a job for bound methods...

import sys
stdwrite = sys.stdout.write
stdwriteln = sys.stdout.writelines

stdwriteln (["Hello ", "world\n"])
Of course, everyone wants something slightly different from their
default I/O stuff. One mans useful shortcut is another mans irritant
that he's constantly having to work around.
A simple formatting utility class is sometimes useful. After all,
formatting isn't just about where the spaces are. Word-wrapping,
indentation levels for paragraphs, bullet points and more can all make
life easy when generating complex console output. I even once
supported simple tables in a text mode output formatter, though not in
Python.

I just hacked the following together, if anyone is interested - it
definitely is not ready for real use, but it might be a useful start
for someone. The constructor optionally takes a callable object, used
to write each line, and a line length. The 'begin' and 'end' methods
do indented blocks, bullets etc. The main output methods are 'write',
'writeall' and 'writeln'.

'writeall' takes a single list parameter, converts every item in the
list using the 'str' function, and outputs each in turn.

'write' uses multiple parameters instead of a single list parameter.

'writeln' is like 'write', but ends the paragraph automatically. I'm
not sure where I got the 'ln' suffix from - either Pascal or Modula 2,
probably. Probably a bad name here, but what the hell.

'para' ends the current paragraph without writing more text.

'begin' normally takes a single string with the indent spaces and
possibly the bullet character. You might use " " for a simple indent,
for instance, or " * " for a bullet point. It can make an all-space
version for follow-on lines itself, but if you want something
different you can override it.

#
# Simple text-mode output formatter
#

import sys
import string

class Formatter :
target = sys.stdout.write
indent = ""
nxtindent = ""
curindent = None
indentstk = []
width = 80
pending = ""
separator = ""
terminator = "\n"

def __init__ (self,
target = sys.stdout.write,
width = 80 ) :
self.target = target
self.width = width

def begin (self, indent=" ", nxtindent=None) :
self.para ()
self.indentstk.append ((self.indent, self.nxtindent))
self.indent = self.nxtindent + indent

if nxtindent == None :
self.nxtindent += " " * len (indent)
else :
self.nxtindent += nxtindent

def end (self) :
self.para ()
self.indent = self.indentstk [-1] [0]
self.nxtindent = self.indentstk [-1] [1]
self.indentstk = self.indentstk [:-1]

def set_modifiers (self, separator = None, terminator = None) :
if separator != None :
self.separator = seperator

if terminator != None :
self.terminator = terminator

def write (self, *strings) :
self.writeall (strings)

def writeall (self, strings) :
t1 = string.join ([str (i) for i in strings], self.separator)

i = t1.find ("\n")

while i >= 0 :
self.pending += t1 [:i]
t1 = t1 [i+1:]
self.flush (True)
self.target ("\n")
i = t1.find ("\n")

self.pending += t1
self.flush (False)

def writeln (self, *strings) :
t1 = string.join ([str (i) for i in strings], self.separator) +
self.terminator

i = t1.find ("\n")

while i >= 0 :
self.pending += t1 [:i]
t1 = t1 [i+1:]
self.flush (True)
self.target ("\n")
i = t1.find ("\n")

self.pending += t1
self.flush (False)

def para (self) :
if self.pending != "" :
self.flush (True)
self.target ("\n")

def flush (self, force) :
if self.pending != "" :
if self.curindent == None :
self.curindent = self.indent

xwidth = self.width - len (self.indent)

while len(self.pending) >= xwidth :
i = xwidth - 1
while (i > 1) and (self.pending [i] != ' ') :
i -= 1
self.target (self.curindent+string.rstrip (self.pending
[:i])+"\n")
self.curindent = self.nxtindent
self.pending=string.lstrip (self.pending [i:])

if force and (len (self.pending) > 0) :
self.target (self.curindent+string.rstrip (self.pending)+"\n")
self.curindent = None
self.pending=""

--
Steve Horne

steve at ninereeds dot fsnet dot co dot uk
Jul 18 '05 #19

P: n/a
Josiah Carlson <jc******@nospam.uci.edu> wrote in
news:c2**********@news.service.uci.edu:
I've wondered, though, whether there couldn't be a different
character instead of a ',' to alter the behavior of print.
Maybe a trailing '+' to indicate that what follows is to
concatenate directly.

And yet I've been able to work around that little annoyance;
it's not that there is no way to format output the way you
want.

It seems that you are saying:

print "hello ", "world" + #-> "hello world"

That looks like "magic syntax", and should rightfully return a
syntax error, because + already has a meaning for most all data
types in Python. Changing the behavior of print when a syntax
error is present, is the wrong thing to do.

The right thing to do (if it were to happen at all) is to make
fileobject.softspace "sticky" under some condition, perhaps
after a call to fileobject.SetSoftSpace(False) (which doesn't
currently exist).


I'm not sure I agree with this entirely. The comma following a
print statement is a sort of magic syntax as it is; it changes the
behavior of the unadorned print statement in a way that has very
little to do with any syntactical meaning a comma would normally
have. The idle thought I mentioned above would just use a different
symbol to alter the behavior of print in a slightly different
fashion. What I actually had in mind, adapting your example, was
something a little different:
print "hello" +
print "nwheels" #-> "hellonwheels"

If a '+' is problematic, it could be some other character. If I use
a print statement in a Python program, from my viewpoint, a
trailing comma signals suppression of newline and adding a space.
In this scenario, a trailing <insert acceptable character here>
would suppress the newline but not add a space. There's not much
difference there.

Having said all that, I'll add that I don't see this as a big
issue, and I don't find it a burden to use an alternative syntax to
achieve the same effect. I don't know how to tell if it's a right
or wrong thing to do. If it were a feature of the language, I'd
probably use it. I've never really understood what it is about the
print statement that bothers some people; it's always seemed
reasonably useful and reasonably intuitive to me. Maybe every
language is destined to have irregular verbs.
--
rzed

Jul 18 '05 #20

P: n/a
> If a '+' is problematic, it could be some other character. If I use
a print statement in a Python program, from my viewpoint, a
trailing comma signals suppression of newline and adding a space.
In this scenario, a trailing <insert acceptable character here>
would suppress the newline but not add a space. There's not much
difference there.
The problem is that checking my keyboard, there exists exactly three
characters without syntactical meanings in Python 2.3; @, $, ?. None of
them make /any/ sort of syntactical sense to me in this context. I hope
that Guido feels the same way.

Having said all that, I'll add that I don't see this as a big
issue, and I don't find it a burden to use an alternative syntax to
achieve the same effect. I don't know how to tell if it's a right
or wrong thing to do. If it were a feature of the language, I'd
probably use it. I've never really understood what it is about the
print statement that bothers some people; it's always seemed
reasonably useful and reasonably intuitive to me. Maybe every
language is destined to have irregular verbs.


I don't know if every language is destined, and I don't find print to be
all that irregular, or really magical, so it seems like we are on the
same page.
- Josiah
Jul 18 '05 #21

P: n/a
Josiah Carlson <jc******@nospam.uci.edu> writes:
If a '+' is problematic, it could be some other character. If I use
a print statement in a Python program, from my viewpoint, a trailing
comma signals suppression of newline and adding a space. In this
scenario, a trailing <insert acceptable character here> would
suppress the newline but not add a space. There's not much
difference there.


The problem is that checking my keyboard, there exists exactly three
characters without syntactical meanings in Python 2.3; @, $, ?. None
of them make /any/ sort of syntactical sense to me in this context. I
hope that Guido feels the same way.


How about two trailing commas:

print foo

now prints foo with a trailing newline.

print foo,

suppresses the trailing newline but adds a trailing space.

print foo,,

can suppress the trailing space as well.
Jul 18 '05 #22

P: n/a
> How about two trailing commas:

print foo

now prints foo with a trailing newline.

print foo,

suppresses the trailing newline but adds a trailing space.

print foo,,

can suppress the trailing space as well.


Do you really want to see the following;

print "hello ",,"world"
IMO, if people really want to have precise control over their program
output, then they should be using sys.stdout.write(), printf-style
string formatting, or both. For me, I see print as a convenience, not
as a one-function-fits-all-for-all-program-output.

- Josiah
Jul 18 '05 #23

P: n/a
Martin,

If you're really serious about this, and willing to champion it,
you should write a PEP. Without a PEP, the idea will be forgotten.
See PEP 1 for instructions:
<http://www.python.org/peps/pep-0001.html>.

-- David Goodger
Jul 18 '05 #24

P: n/a
Josiah Carlson wrote:
It seems that you are saying:

print "hello ", "world" + #-> "hello world"

That looks like "magic syntax", and should rightfully return a syntax
error, because + already has a meaning for most all data types in
Python. Changing the behavior of print when a syntax error is present,
is the wrong thing to do.


It can be done the other way around:
class Mystr(str): .... def __pos__(self):
.... if self.endswith(' '): return self[:-1]
.... else: return self
.... m = Mystr("abc ")
print +m, "bla"

abc bla

....although I prefer sys.stdout.write.

Gerrit.

--
Weather in Twenthe, Netherlands 02/03 14:55 UTC:
6.0°C Few clouds mostly cloudy wind 5.8 m/s WNW (57 m above NAP)
--
Asperger's Syndrome - a personal approach:
http://people.nl.linux.org/~gerrit/english/

Jul 18 '05 #25

P: n/a
On Mon, 01 Mar 2004 21:42:21 GMT, "Rainer Deyke" <ra*****@eldwood.com>
wrote:
Josiah Carlson wrote:
The right thing to do (if it were to happen at all) is to make
fileobject.softspace "sticky" under some condition, perhaps after a
call to fileobject.SetSoftSpace(False) (which doesn't currently
exist).


The right thing to do is to put make stdout a builtin and deprecate the
print statement. The "smart" behavior of the print statement causes more
trouble than it's worth. I admit that I use the print statement myself
occasionally, but only because 'sys.stdout.write' is too long to type all
the time, and never with more than one argument.


The 'print' statement is just shortcut for 'sys.stdout.write' with
some convenience features suitable for most users. If you need
something else, just define your own shortcut, don't deprecate a
statement that is exactly what most users want.
wrt = sys.stdout.write
wrt('abc'); wrt('xyz\n'); wrt('abc'); wrt('xyz')

abcxyz
abcxyz

Now you have explicit control over the \n, and the new statement
(including parens) is the same number of characters as 'print'.

We need to resist the temptation to *change* the core language, when
*extending* it using normal function syntax is so easy.

Note: You can also change the behavior of 'print' by redefining
'sys.stdout.write'. You can even hide that redefinition deep in some
imported module, where future maintainers of your code will never find
it. :>)

-- Dave

Jul 18 '05 #26

P: n/a
[David Goodger <go*****@python.org>]
you should write a PEP. Without a PEP, the idea will be forgotten.


Good advice, good encouragement, thanks.

I'd really like to. But unfortunately I've discovered the weak point
in my own argumentation: a new keyword could and probably would break
existing code. Therefore I can't go for a PEP until I have a better
idea.

Ok, then let's use some wrappers or helper functions. Here's the one I
currently like:

#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""Do some experiments on write statements."""

__author__ = "Martin Bless, 2004-03-03"

class Writer:

def __init__(self,writer=None):
if writer is None:
import sys
self.writer = sys.stdout
else:
self.writer = writer

def write(self,*args):
for arg in args:
self.writer.write(str(arg))

__call__ = write

def to(self,writer,*args):
for arg in args:
writer.write(str(arg))

write = Writer()
NL = '\n'
import sys
stderr = Writer(sys.stderr)

if __name__=="__main__":
import sys
outfile = sys.stdout or file('demo_tempfile','w')
write('#', '-->'*10, NL)
write('Starting.',NL)
write(__doc__,NL)
write("write(1,2,3,4,NL)=>", 1,2,3,4,NL)
write("write('This',' ','is',' ','a',' ','demo.',NL)=>",
'This',' ','is',' ','a',' ','demo.',NL)
write.to( outfile,"write.to(outfile,5,6,7,8,NL)=>",5,6,7,8,N L)
stderr("stderr('A number in parentheses: (', 77, ').', NL)=>",
'A number in parentheses: (',77,').',NL)
write('Done.',NL)
write('#', '<--'*10, NL)

"""Output should be:
#-->-->-->-->-->-->-->-->-->-->
Starting.
Do some experiments on write statements.
write(1,2,3,4,NL)=>1234
write('This',' ','is',' ','a',' ','demo.',NL)=>This is a demo.
write.to(outfile,5,6,7,8,NL)=>5678
stderr('A number in parentheses: (',77,').',NL)=>A number in
parentheses: (77).
Done.
#<--<--<--<--<--<--<--<--<--<--
"""

This comes pretty close to what I was aiming at. But of course it's
just my version and different people will create different solutions.

mb - Martin Bless
Jul 18 '05 #27

P: n/a
["Rainer Deyke" <ra*****@eldwood.com>]
but only because 'sys.stdout.write' is too long to type all
the time, and never with more than one argument.


Yes, I feel it's a pity that the standard write method of file objects
doesn't take multiple arguments. Would take some of the pressure.

One thing I can do since Python-2.2 is to inherit from 'file' and add
for example a 'writem' (write many, write multiple) method. This does
work.

Unfortunately it seems I can't add that 'writem' method to sys.stdout,
as the following shows.

Anybody any ideas?
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""Test file object."""

__author__ = "Martin Bless, 2004-03-03"

if 1 and "this does work":
class MyFile(file):

def writem(self,*args):
"Method to write many arguments."
for arg in args:
self.write(str(arg))

f2name = 'xxxtempfile'
f2 = MyFile(f2name,'w')
f2.writem(1,2,3,4)
f2.close()
if 1 and "this does not work with sys.stdout":
"""
Attempt to add a method to a class at runtime.
See Python Cookbook or ASPN,
Object-Oriented Programming, Brett Cannon.
"""
import sys
def writem(self,*args):
"Function to be turned into a method.."
for arg in args:
self.write(str(arg))
# will not work
setattr(sys.stdout.__class__,'writem',writem)

"""The above 'setattr' will give this error:
Traceback (most recent call last):
File "test_file_object.py", line 33, in ?
setattr(sys.stdout.__class__,'writem',writem)
TypeError: can't set attributes of built-in/extension type 'file'
"""

mb - Martin Bless

Jul 18 '05 #28

P: n/a
On Wed, 03 Mar 2004 10:32:34 GMT, m.*****@gmx.de (Martin Bless) wrote:
["Rainer Deyke" <ra*****@eldwood.com>]
but only because 'sys.stdout.write' is too long to type all
the time, and never with more than one argument.
Yes, I feel it's a pity that the standard write method of file objects
doesn't take multiple arguments. Would take some of the pressure.

One thing I can do since Python-2.2 is to inherit from 'file' and add
for example a 'writem' (write many, write multiple) method. This does
work.

Unfortunately it seems I can't add that 'writem' method to sys.stdout,
as the following shows.


Why do you want to do this, when it is so easy to define your own
class to do exactly what you want (as in your example below)?
Anybody any ideas?
I think Ruby has what you need. The default print method requires an
explicit "\n" on every line. To me, this makes normal code look ugly,
but your preference is valid too.

Ruby also allows you to redefine its built-in classes, so if you need
that level of flexibility, this language may be a better choice.

Lua is also a possibility, but I know even less of that language.

Python differs from other languages in that it tries to keep a common
core language that is the same for everyone, while still allowing
extensions like your example below. The arguments against providing
more flexibility (e.g. a builtin macro language) are strong. See for
example:
http://groups.google.com/groups?selm...s1.newsguy.com

To add a variation of the print statement to the Python language, you
would need to demonstrate a real need for the change, not just a
personal preference for leaving out the " ". Generalizing the
'sys.stdout.write()' method to include multiple arguments might be
more acceptable. If you do a PEP along these lines, I would
emphasize:
- does not break existing code
- some good examples where this would have an advantage over current
best practices. Your choice of integer arguments in the example below
is wise. Had it been strings, the current solution would be to just
put '+' between the pieces instead of ','

-- Dave
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""Test file object."""

__author__ = "Martin Bless, 2004-03-03"

if 1 and "this does work":
class MyFile(file):

def writem(self,*args):
"Method to write many arguments."
for arg in args:
self.write(str(arg))

f2name = 'xxxtempfile'
f2 = MyFile(f2name,'w')
f2.writem(1,2,3,4)
f2.close()
if 1 and "this does not work with sys.stdout":
"""
Attempt to add a method to a class at runtime.
See Python Cookbook or ASPN,
Object-Oriented Programming, Brett Cannon.
"""
import sys
def writem(self,*args):
"Function to be turned into a method.."
for arg in args:
self.write(str(arg))
# will not work
setattr(sys.stdout.__class__,'writem',writem)

"""The above 'setattr' will give this error:
Traceback (most recent call last):
File "test_file_object.py", line 33, in ?
setattr(sys.stdout.__class__,'writem',writem)
TypeError: can't set attributes of built-in/extension type 'file'
"""

mb - Martin Bless


Jul 18 '05 #29

P: n/a
On Wed, 03 Mar 2004 10:32:34 GMT, m.*****@gmx.de (Martin Bless) wrote:
["Rainer Deyke" <ra*****@eldwood.com>]
but only because 'sys.stdout.write' is too long to type all
the time, and never with more than one argument.
If the only remaining issue is multiple arguments:
import sys
def wrt(*args): for arg in args:
sys.stdout.write(arg)
wrt('abc','xyz\n','abc',1,2,3) abcxyz
abc123

-- Dave

Yes, I feel it's a pity that the standard write method of file objects
doesn't take multiple arguments. Would take some of the pressure.

One thing I can do since Python-2.2 is to inherit from 'file' and add
for example a 'writem' (write many, write multiple) method. This does
work.

Unfortunately it seems I can't add that 'writem' method to sys.stdout,
as the following shows.

Anybody any ideas?
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""Test file object."""

__author__ = "Martin Bless, 2004-03-03"

if 1 and "this does work":
class MyFile(file):

def writem(self,*args):
"Method to write many arguments."
for arg in args:
self.write(str(arg))

f2name = 'xxxtempfile'
f2 = MyFile(f2name,'w')
f2.writem(1,2,3,4)
f2.close()

Jul 18 '05 #30

P: n/a
m.*****@gmx.de (Martin Bless) writes:
I'd really like to. But unfortunately I've discovered the weak point
in my own argumentation: a new keyword could and probably would break
existing code. Therefore I can't go for a PEP until I have a better
idea.


You could suggest adding an "attribute" to the existing keyword:

print foo,bar # print with spaces
print.n foo,bar # print without spaces

I don't care too much for this idea but it would solve your immediate
concern.
Jul 18 '05 #31

This discussion thread is closed

Replies have been disabled for this discussion.