[Python-Dev] Challenge about print >> None

Guido van Rossum guido@beopen.com
Mon, 11 Sep 2000 18:31:35 -0500

> >>>>> "GvR" == Guido van Rossum <guido@beopen.com> writes:
>   GvR> Don't think of it as
>   GvR>   print >>None, args
>   GvR> Think of it as
>   GvR>   def func(file=None):
>   GvR>     print >>file, args
> Huh?  Don't you mean think of it as:
> def func(file=None):
>     if file is None:
>        import sys
>        print >>sys.stdout, args
>     else:
> 	print >>file, args

I meant what I said.  I meant that you shouldn't think of examples
like the first one (which looks strange, just like "".join(list) does)
but examples like the second one, which (in my eye) make for more
readable and more maintainable code.

> At least, I think that's why I find the use of None confusing.  I find
> it hard to make a strong association between None and sys.stdout.  In
> fact, when I was typing this message, I wrote it as sys.stderr and
> only discovered my error upon re-reading the initial message.

You don't have to make a strong association with sys.stdout.  When the
file expression is None, the whole ">>file, " part disappears!

Note that the writeln() function, proposed by many, would have the
same behavior:

  def writeln(*args, file=None):
      if file is None:
          file = sys.stdout
      ...write args...

I know that's not legal syntax, but that's the closest
approximation.  This is intended to let you specify file=<some file>
and have the default be sys.stdout, but passing an explicit value of
None has the same effect as leaving it out.  This idiom is used in
lots of places!

--Guido van Rossum (home page: http://www.pythonlabs.com/~guido/)