473,761 Members | 10,276 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pre-PEP: Dynamically evaluating default function arguments

One of the most common bugs that people have on the Python Tutor list
are caused by the fact the default arguments for functions are
evaluated only once, not when the function is called. The solution to
this is usually to use the following idiom:

def write_stuff(stu ff=None):
"""Function to write its argument.

Defaults to whatever is in the variable "things"
"""
if stuff is None:
stuff = things
print stuff

However, it would be much more intuitive and concise if the following
could be done instead, but with the guarantee that changes in the
variable 'things' will be noticed:

def write_stuff(stu ff=things):
print stuff

This would instead print whatever is in things when the function is
defined.

The goal of this pre-PEP is to make it so that the default arguments
are evaluated dynamically instead of when the function is created. As
this is a pre-PEP, the details have not been finalized yet. One of the
first details is whether or not the default argument should be checked
to make sure it exists before the function is called. I think it would
make the most sense if things were evaluated when the function was
defined but the result was not saved and was reevaluated whenever the
function is called. This might not be the best way to do it, though,
and it might be better to treat it just like a regular equals sign.

As with any additional dynamic properties added, there is the
possibility of some errors to go uncaught and some. Here is an example
of some hypothetical (but unlikely) code that would cause an error as
a result of this change:
x = 5
def return_somethin g(stuff=x): return stuff return_somethin g() 5 x += 1
return_somethin g() #dynamic now 6 del x
return_somethin g()

Traceback (most recent call last):
File "<input>", line 1, in ?
NameError: name 'x' is not defined

To me, this seems like the logical behavior, but there is still the
possiblility of some programs being broken. A way to preserve
backwards compatability could be to store the initial evaluation of
the default and use it to fall back on if the variable needed isn't
around anymore, but this seems overly complicated.

Daniel Ehrenberg
Jul 18 '05 #1
3 1826
That proposal gets "-All" from me. (or, at least, I think that's what I
mean. Maybe I just mean "None", I couldn't stand that other thread)

Reams of code depend on default arguments working as they do today. For
instance:
l = []
for i in range(10):
l.append(lambda x, y=i: x+y)
or
def fib(x, y={0: 1, 1: 1}):
assert x >= 0
if not y.has_key(x):
y[x] = fib(x-1) + fib(x-2)
return y[x]
or
def stack():
def push(x, l=[]):
l.append(x)
def pop(l=push.func _defaults[0]):
return l.pop()
return push, pop

It's not clear exactly how this feature would work. What additional
state will you store with function objects to make it work? Right now,
it works like this:
def f(l=x):
pass
is equivalent to
_magic = x
def f(*args):
assert len(args) < 2
if args: l = args[0]
else: l = _magic
you're proposing something more like
_magic = lambda: x
def f(*args):
assert len(args) < 2
if args: l = args[0]
else: l = _magic()
you've just added one additional function call overhead for each
defaulted argument, plus the time to evaluate the expression 'x', even
in cases where it makes no difference. Here's a case where the
programmer has performed a micro-optimization that will probably be
slower after your change (even though the program's meaning is not
changed):
def log10(x, l=math.log, l10=math.log(10 )):
return l(x)/l10

That leaves the case where you actually want the default argument value
to depend on the current program's state, as below:
def log(s, when=time.time( )):
print >>stderr, time.asctime(wh en), s
I think it's better to write
def log(s, when=None):
if when is None: when = time.time()
print >>stderr, time.asctime(wh en), s
because it makes calling code easier, too:
def log_with_prefix (p, s, when=None):
log("%s: %s" % (p, s), when)
instead of repeating the default argument everwhere you may call it both ways
def log_with_prefix (p, s, when=time.time( )):
log("%s: %s" % (p, s), when)
or having to test at each place you call:
def log_with_prefix (p, s, when=None):
if when is None:
log("%s: %s" % (p, s))
else:
log("%s: %s" % (p, s), when)

Jeff

Jul 18 '05 #2
"Daniel Ehrenberg" <Li************ @yahoo.com> wrote in message
news:71******** *************** ***@posting.goo gle.com...
One of the most common bugs that people have on the Python Tutor list
are caused by the fact the default arguments for functions are
evaluated only once, not when the function is called. The solution to
this is usually to use the following idiom:
[snip]

It's an interesting proposal, but outside of the possible
breakage, there is one really major problem:

Where is the variable going to come from on the function
call? If it comes from the original context, it's static so why
bother, and if it comes from the caller's context, you're
causing a *huge* amount of coupling, as well as a substantial
slowdown to do a search of the calling chain and the global
context.

You can't even make it optional: use the original
value if it's not defined in the caller's context. If you
do that, you're still exposing the names to the caller
as names he has to avoid when writing the calling
routine.

To put a somewhat positive spin on it though,
it is a significant novice problem. Given that you
don't want to change the language semantics, what's
the next possible way to fix it?

Compare PEP's 215 and 292. Both of these
do dynamic variable fills, but they have one
critical difference: the template is visible, and not
off in a function or method definition somewhere.
Even so, there are significant issues that have to
be resolved.

John Roth


Daniel Ehrenberg

Jul 18 '05 #3
I'm sorry I wasted your time, everyone.
Jul 18 '05 #4

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

Similar topics

2
3105
by: GriffithsJ | last post by:
Hi I have been given some text that needs to be displayed on a web page. The text is pre-formatted (includes things like lists etc) and displays okay if I wrap it using the <pre/> tag. However, the font used is rather "naff" and looks too different to the rest of my web page. I'm not sure how I can (or even whether I can) override the font used with the <pre/> tag. If not, is there another tag I can use to display pre-formatted...
2
3706
by: Porthos | last post by:
Hi All, I'm building an XSL document that puts two types of information in a table dimension: preformatted data and data extracted from my XML document (see below) <table> <tr>
7
18534
by: Alan Illeman | last post by:
How do I set several different properties for PRE in a CSS stylesheet, rather than resorting to this: <BODY> <PRE STYLE="font-family:monospace; font-size:0.95em; width:40%; border:red 2px solid; color:red;
5
718
by: Michael Shell | last post by:
Greetings, Consider the XHTML document attached at the end of this post. When viewed under Firefox 1.0.5 on Linux, highlighting and pasting (into a text editor) the <pre> tag listing will preserve formatting (white space and line feeds). However, this is not true when doing the same with the <code> tag listing (it will all be pasted on one line with multiple successive spaces treated as a single space) despite the fact that...
1
4741
by: R0bert Nev1lle | last post by:
Here's my next IE challenge (or frustration). It deals with the overflow attribute. Overflow property was a challenge on my page since the page emulates position fixed for IE. The present scenario deals with the pre element. Sometimes the content in the pre container exceed the parent container's width. IE expands the parent containers width as a result. The workaround for this scenario relates to the overflow property and using a...
8
3789
by: Jarno Suni not | last post by:
It seems to be invalid in HTML 4.01, but valid in XHTML 1.0. Why is there the difference? Can that pose a problem when such a XHTML document is served as text/html?
7
2749
by: Rocky Moore | last post by:
I have a web site called HintsAndTips.com. On this site people post tips using a very simply webform with a multi line TextBox for inputing the tip text. This text is encode to HTML so that no tags will remain making the page safe (I have to convert the linefeeds to <BR>s because the Server.EncodeHTML does not do that it seems). The problem is that users can use a special tag when editing the top to specify an area of the tip that will...
9
5548
by: Eric Lindsay | last post by:
I can't figure how to best display little snippets of shell script using <pre>. I just got around to organising to bulk validate some of my web pages, and one of the problems occurs with Bash shell pieces like this: <pre><code> #!/bin/sh ftp -i -n ftp.server.com&lt; &lt;EOF user username password epsv4 cd /
7
4857
by: Paul Connolly | last post by:
char *s = "Hello"; s = 'J'; puts(s); might print "Jello" in a pre-ANSI compiler - is the behaviour of this program undefined in any pre-ANSI compiler - or would it always have printed "Jello" with a pre-ANSI compiler? In gcc with the "writable-strings" option this program prints Jello If there were more than one semantics for what this progran did under a
12
5578
by: Vadim Guchenko | last post by:
Hello. I'm using the following code: <html> <head> <style type="text/css"> pre {display: inline;} </style> </head>
0
9531
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
9345
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
10115
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...
1
9905
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
9775
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6609
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3456
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.