side effects on *some* default parameters

logistix logistix at zworg.com
Fri Feb 14 18:49:00 EST 2003


Joe Grossberg <jgrossberg at matrixgroup.net> wrote in message news:<mailman.1045154045.19349.python-list at python.org>...
> Eric Max Francis writes:
> > Because in Python, default argument values are only created once.  The
> > FAQ addresses this, and it gets asked about once a week in the group.
> 
> OK please allow me to rephrase:
> 
> *Why* is this better than the alternative (i.e. default argument values get created every time the method/function is called without the parameter)? 
> 
> Is it how all (respected) languages are designed? Is it because of "scope nasties" we'd encounter otherwise? Is it because of how Python is compiled? Or was it an early, arbitrary language design decision that we're stuck with, for better or for worse?
> 
> In other words, I'm not asking "Does Python do this?" -- I'm asking "Why does Python do this?"

Because you want to be able to verify that keyword values can be
successfully evaluated when the function is defined.  In the below
example, would you rather have the error occur then, or in some
completely random script on line 1951?  Also note the second part, it
shows that every time the 'def' statement is encountered, not just at
compile time:

PythonWin 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on
win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au)
- see 'Help/About PythonWin' for further copyright information.
>>> def foo(a,b=c):
... 	pass
... 
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'c' is not defined
>>> 
>>> 
>>> def makeFun():
... 	def foo(a=[]):
... 		a.append("foo")
... 		print a
... 	return foo
... 
>>> makeFun()()
['foo']
>>> makeFun()()
['foo']
>>> makeFun()()
... 
['foo']
>>>




More information about the Python-list mailing list