473,797 Members | 3,183 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.String IO()
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.stde rr,

descriptions=1, verbosity=1):
Jul 18 '05 #1
3 1778
fB*******@web.d e (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.goo gle.com...
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
15578
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 = myList
5
1221
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
15399
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
1585
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 & cycle, const string &username="true")
5
2310
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 __init__(self, myarr=): self.myarr = myarr
6
1369
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 out whether the value of y is # the default argument, or user-supplied?
35
2254
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 code. This example is trivial and has design issues, but it demonstrates a problem I've seen in production systems: def main(argv = ): 'print out arguments with BEGIN and END' argv.insert(1, "BEGIN")
4
3433
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 “tblStatusReports” containing the “StafferID” (link to Staffer table), the “ProjectID” (link to Projects table), a “Date” field, and a “Notes” field. There is a main form, “frmStaffEntry,” with a subform, “frmStatusReports,” for a user to...
24
2528
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 finally, and painfully, fade away than another one starts up. I suggest that Python should raise warnings.RuntimeWarning (or similar?) when a function is defined with a default argument consisting of a list, dict or set. (This is not meant as an...
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9537
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10469
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10246
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10209
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9066
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4135
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3750
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.