| Store | Cart

"print" as function not statement

From: Duncan Booth <m...@privacy.net>
8 Mar 2004 08:31:48 GMT
Leif K-Brooks <eurleif at ecritters.biz> wrote in 
news:QjV2c.302$_43.225384 at newshog.newsread.com:

> In any case, I did a quick Python implementation of the show function. > All bugs are features. :-)> > import sys> > def show(*objects, **parameters):>      seperator = parameters.get('seperator', ' ')>      trailer = parameters.get('trailer', '\n')>      to = parameters.get('to', sys.stdout)>      first = 1>      for object in objects:>          if not first:>              to.write(str(seperator))>          to.write(str(object))>          first = 0>      to.write(str(trailer))>      if len(objects) == 1:>          return objects[0]>      else:>          return objects> 

You need a bit more checking to be sure nobody tried to pass in any 
unexpected keyword arguments, and your output loop is a bit messy.

def show(*args, **kw):
        separator = kw.get('separator', ' ')
        trailer = kw.get('trailer', '\n')
        to = kw.get('to', sys.stdout)
        for keyword in kw:
            if not keyword in ('separator', 'trailer', 'to'):
                raise TypeError(
'show() got an unexpected keyword argument' + keyword)
        to.write(separator.join([ str(arg) for arg in args]))
        to.write(trailer)
        if len(args)==1:
            return args[0]
        else:
            return args

Things wrong with the proposal:

The arguments that this function accepts don't follow the pattern of any 
other Python functions, so we need 6 lines of code just to unscramble them. 
This should be a big red warning flag: don't go that way.

The 4 lines of code to work out the result are another red flag warning 
that the result is going to cause confusion for users.

The real work of the function can be replaced by 2 lines of code, or 1 if 
you don't mind copying the output string an extra time. So the penalty is 
to add an inconsistent function to the language that everyone has to learn 
in return for replacing one line of code with a (possibly) shorter line of 
code.

If you need this, then just hardwire your separator and terminator and 
write a custom one line function for each different style of output. 
Personally I think I'll stick to using format strings.

Recent Messages in this Thread
Mark Kamikaze Hughes Mar 08, 2004 01:36 am
John Roth Mar 08, 2004 02:38 am
Leif K-Brooks Mar 08, 2004 07:32 am
Duncan Booth Mar 08, 2004 08:31 am
Leif K-Brooks Mar 08, 2004 10:36 am
A.M. Kuchling Mar 08, 2004 01:29 pm
Heather Coppersmith Mar 08, 2004 12:56 pm
David MacQuigg Mar 09, 2004 09:04 pm
Aahz Mar 10, 2004 10:43 am
Peter Otten Mar 10, 2004 12:52 pm
David MacQuigg Mar 10, 2004 03:32 pm
Messages in this thread