just another default argument value gotcha
Michael Hudson
mwh at python.net
Mon Dec 29 09:08:14 EST 2003
fBechmann at web.de (Frank Bechmann) writes:
> Eventually most of you will not learn much from this because it's just
> another event in the 'default argument value gotcha' series, but
> because it cost me some hours yesterday to spot this 'error' in a
> famous python tool I thought it might still help other people to save
> some time.
>
> I tried to use some method which was documented to write to
> 'sys.stdout' per default so that changing 'sys.stdout' to bind to
> another object should allow to get grip on the method's output. but
> that didn't work - reason was that that 'sys.stdout' was used as
> default argument value for the method.
FWIW, I think this is precisely the reason that "print >>None, ..."
prints to sys.stdout. It lets you write
> The following code describes it better then my english can do, so as
> it seems for me, one should make sure to use the 'f2' variant.
>
> import StringIO, sys
>
> def f1(msg, out=sys.stdout):
> out.write("%s\n" % msg)
>
> def f2(msg, out=None):
> if not out:
> out = sys.stdout
> out.write("%s\n" % msg)
either of these as
def f3(msg, out=None):
print >>out, msg
Cheers,
mwh
--
For their next act, they'll no doubt be buying a firewall
running under NT, which makes about as much sense as
building a prison out of meringue. -- -:Tanuki:-
-- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html
More information about the Python-list
mailing list