473,320 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

just another default argument value gotcha

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. 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)

if __name__ == "__main__":
buf = sys.stdout = StringIO.StringIO()
f1("calling f1")
f2("calling f2")
data = buf.getvalue()
buf.close()
sys.stdout = sys.__stdout__
print "=========\n", data

results in:

calling f1 <-- written directly by 'f1'
========== => redirection didn't work
calling f2 <-- written from data stored in 'buf'
running the following greps on this machine brought only 2 possible
spots, but that doesn't mean too much since this is our gaming
computer with only a very basic python installation; eventually
someone with a real huge package list would bring up more hits:

$ find . -name '*.py' -exec grep -H '\bdef\b.*\(.*\=sys.stdout.*\)[
\t]*:' \{} \;
./test/test_grammar.py:def tellme(file=sys.stdout): $ find . -name '*.py' -exec grep -H '\bdef\b.*\(.*\=sys.stderr.*\)[
\t]*:' \{} \; ./unittest.py: def __init__(self, stream=sys.stderr,

descriptions=1, verbosity=1):
Jul 18 '05 #1
3 1747
fB*******@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
Jul 18 '05 #2

"Frank Bechmann" <fB*******@web.de> wrote in message
news:db**************************@posting.google.c om...
Eventually most of you will not learn much from this because it's just
another event in the 'default argument value gotcha' series, but
There are two issues: when the default value is determined and whether it
is mutable. The concern here is timing.
I tried to use some method which was documented to write to
'sys.stdout' per default
The meaning of the expression 'sys.stdout' may depend on when it is
evaluated.
so that changing 'sys.stdout' to bind to
another object should allow to get grip on the method's output.
If you change the binding before the evaulation, you will affect the
result; otherwise not and your inference is incorrect.
but that didn't work - reason was that that 'sys.stdout' was used as
default argument value for the method.
Without the doc quoted, I can't tell whether it was misleading or if you
misread it. If the doc said 'default argument value' then it was exactly
right.
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.
The code to use is the one that gives the result you want. To give a
function parameter a default *value*, evaluated once and good for all
function calls, write the expression yielding the value (a constant object)
in the definition-time header as in
import StringIO, sys

def f1(msg, out=sys.stdout):
out.write("%s\n" % msg)
To me, and apparently to GvR, this is what 'default value' means. If you
want a backup *expression*, conditionally evaluated at each function call
(and therefore potentially yielding different objects in different function
calls), write the expression in the run-time body as in
def f2(msg, out=None):
if not out:
out = sys.stdout
out.write("%s\n" % msg)


In this case, I see passing an value for param 'out' via the
runtime-evaluated global attribute sys.stdout as an alternate (implicit)
arg passing mechanism, one that is fairly common. Simplifying f2 gives

def f3(msg):
out = sys.stdout
out.write(("%s\n" % msg)

The added complexity of f2 gives one the option of passing 'out' either
directly in the call or indirectly via the global. I would only use it if
one needed and were going to use the added flexibility. The authors of the
method you used did not think it necessary.

Another issue your problem touches on is the ambiguity of 'builtin' names
like 'sys' and 'sys.stdout'. When the docs use such names, they sometimes
to usually to always mean the objects originally bound to the name on
interpreter startup, ignoring any possible later rebindings within a
program execution. The reader is expected to interprete the text
immediately using the default, pre-startup bindings. For example, in
'functions return None by default', 'None' means the singleton NoneType
object, not its runtime binding. Similarly, 'sys.stdout' is sometimes used
to refer specifically to its original rather than 'current' binding. I
would tend to assume this for library modules unless the doc, the code, or
experiment showed otherwise.

Terry J. Reedy
Jul 18 '05 #3
thx for that tip, it worked as predicted.

nevertheless it seems to be an error if some function/method uses the
'sys.stdout' default value but *not* the 'print >>out' syntax. and
this in turn means that my simple grep error finder doesn't help too
much, you still have to look at the code of the matching
functions/methods.
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: Alex Panayotopoulos | last post by:
Hello all, Maybe I'm being foolish, but I just don't understand why the following code behaves as it does: - = - = - = - class listHolder: def __init__( self, myList= ): self.myList =...
5
by: Paul Sweeney | last post by:
The python tutorial gives the following example to demonstrate the fact that default args are only evaluated once: def f(a,L=): L.append(a) return L print f(1),f(2),f(3)
5
by: Dave Vandervies | last post by:
If I feed this to g++: -------- int foo(int i=42); int foo(int i=42) { return i; } -------- It says (with -W -Wall -ansi -pedantic):
11
by: puzzlecracker | last post by:
not sure of the stardard: which one is right, if both which one is preferable? class FOO{ void foo(const string &, const string &username="true"); ..... } void FOO::foo(const string &...
5
by: netvaibhav | last post by:
Hi All: Here's a piece of Python code and it's output. The output that Python shows is not as per my expectation. Hope someone can explain to me this behaviour: class MyClass: def...
6
by: Igor V. Rafienko | last post by:
Hi, I was wondering whether it was possible to find out which parameter value is being used: the default argument or the user-supplied one. That is: def foo(x, y="bar"): # how to figure...
35
by: bukzor | last post by:
I've found some bizzare behavior when using mutable values (lists, dicts, etc) as the default argument of a function. I want to get the community's feedback on this. It's easiest to explain with...
4
by: JHite | last post by:
I am using Access 2003 on Windows XP. This is a simple database that contains “tblStaffers” containing names of the office staffers, “tblProjects” containing names of the office projects, and...
24
by: Steven D'Aprano | last post by:
Sometimes it seems that barely a day goes by without some newbie, or not- so-newbie, getting confused by the behaviour of functions with mutable default arguments. No sooner does one thread...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.