473,394 Members | 2,002 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,394 software developers and data experts.

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(stuff=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(stuff=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_something(stuff=x): return stuff return_something() 5 x += 1
return_something() #dynamic now 6 del x
return_something()

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 1808
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(when), s
I think it's better to write
def log(s, when=None):
if when is None: when = time.time()
print >>stderr, time.asctime(when), 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.google.c om...
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
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. ...
2
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
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...
5
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...
1
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...
8
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
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...
9
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...
7
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"...
12
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...
0
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...

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.