469,271 Members | 1,049 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,271 developers. It's quick & easy.

Keyword arguments - strange behaviour?

Can anyone explain the behaviour of python when running this script?
def method(n, bits=[]): .... bits.append(n)
.... print bits
.... method(1) [1] method(2) [1, 2]

It's the same in python 1.5, 2.3 and 2.4 so it's not a bug. But I
expected the variable "bits" to be re-initialised to an empty list as
each method was called. Whenever I explain optional keyword arguments
to someone I have usually (wrongly as it turns out) said it is
equivalent to:
def method(n, bits=None): .... if bits is None:
.... bits=[]
.... bits.append(n)
.... print bits
.... method(1) [1] method(2)

[2]

Is there a good reason why these scripts are not the same? I can
understand how/why they are different, it's just not what I expected.
(It seems strange to me that the result of the first method can only be
determined if you know how many times it has already been called)

Is this behaviour what you would (should?) intuitively expect?
Thanks,

Brian

Jul 18 '05 #1
24 1815
br********@securetrading.com wrote:
Can anyone explain the behaviour of python when running this script? (...)
Is there a good reason why these scripts are not the same? I can
understand how/why they are different, it's just not what I expected.
(It seems strange to me that the result of the first method can only be
determined if you know how many times it has already been called)


see "python gotchas":
<http://www.ferg.org/projects/python_gotchas.html#bct_sec_5>

bye.

--
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
<#me> a foaf:Person ; foaf:nick "deelan" ;
foaf:weblog <http://www.netspyke.com/> .
Jul 18 '05 #2
br********@securetrading.com wrote:
Can anyone explain the behaviour of python when running this script?


the language reference has the full story:

http://www.python.org/doc/2.4/ref/function.html

"Default parameter values are evaluated when the function
definition is executed"

</F>

Jul 18 '05 #3
wrote:
Can anyone explain the behaviour of python when running this script?
def method(n, bits=[]): ... bits.append(n)
... print bits
... method(1) [1] method(2)

[1, 2]

It's the same in python 1.5, 2.3 and 2.4 so it's not a bug. But I
expected the variable "bits" to be re-initialised to an empty list as
each method was called. Whenever I explain optional keyword arguments
to someone I have usually (wrongly as it turns out) said it is
equivalent to:


<snipped erroneous comparison>

No, it is closer to:

# Assume you have done this earlier:
import new
def _realmethod(n, bits):
bits.append(n)
print bits

# The def is roughly equivalent to this:
_defaultArgs = ([], )
method = new.function(_realmethod.func_code, globals(), 'method',
_defaultArgs)

Each time you re-execute the def you get a new set of default arguments
evaluated, but the result of the evaluation is simply a value passed in to
the function constructor.

The code object is compiled earlier then def creates a new function object
from the code object, the global dictionary, the function name, and the
default arguments (and any closure as well, but its a bit harder to
illustrate that this way).

Jul 18 '05 #4
Thanks, this makes perfect sense. The phrase which sums it up neatly is
"Default parameter values are evaluated when the function definition is
executed"

However, is there a good reason why default parameters aren't evaluated
as the function is called? (apart from efficiency and backwards
compatibility)? Is this something that's likely to stay the same in
python3.0?

I'm really looking for a neat way to do the following:

def method(a,b,opt1=None,opt2=None,opt3="",opt4=None):
if opt1 is None: opt1=[]
if opt2 is None: opt2={}
if opt4 is None: opt4=[]

Python syntax is normally so neat but this just looks a mess if there
are lots of parameters.

Jul 18 '05 #5
<br********@securetrading.com> wrote:
However, is there a good reason why default parameters aren't evaluated
as the function is called? (apart from efficiency and backwards compatibility)?


how would you handle this case:

def function(arg=otherfunction(value)):
return arg

</F>

Jul 18 '05 #6
def function(arg=otherfunction(value)):
return arg

My expectation would have been that otherfunction(value) would be
called if (and only if) the arg keyword parameter was missing from the
function() call (ie. the optional value is evaluated the lazy way).
Also, otherfunction would be called each and every time this function()
is called without the arg keyword. (At least, I would have assumed this
before today)

Still, I can see why it's been implemented the way it has, it just
seems a shame there isn't a neat shortcut to default lots of optional
arguments to new mutable objects. And since I'm not the only one to
fall into this trap it makes me wonder why the default behaviour isn't
made to be what most people seem to expect?

Jul 18 '05 #7
<br********@securetrading.com> wrote:
def function(arg=otherfunction(value)):
return arg

My expectation would have been that otherfunction(value) would be
called if (and only if) the arg keyword parameter was missing from the
function() call (ie. the optional value is evaluated the lazy way).


what otherfunction? what value?

</F>

Jul 18 '05 #8
Hi,

I cannot see any strange behavior. this code works exacly as you and I
suspect:
def otherfunction(x) : .... return x
.... def function(arg=otherfunction(5)) : .... return arg
.... function(3) 3 function()
5

Or is this not what you excepted?

- harold -

On 21.12.2004, at 15:47, br********@securetrading.com wrote:
def function(arg=otherfunction(value)):
return arg

My expectation would have been that otherfunction(value) would be
called if (and only if) the arg keyword parameter was missing from the
function() call (ie. the optional value is evaluated the lazy way).
Also, otherfunction would be called each and every time this function()
is called without the arg keyword. (At least, I would have assumed this
before today)

Still, I can see why it's been implemented the way it has, it just
seems a shame there isn't a neat shortcut to default lots of optional
arguments to new mutable objects. And since I'm not the only one to
fall into this trap it makes me wonder why the default behaviour isn't
made to be what most people seem to expect?

--
http://mail.python.org/mailman/listinfo/python-list

--
Freunde, nur Mut,
Lächelt und sprecht:
Die Menschen sind gut --
Bloß die Leute sind schlecht.
-- Erich Kästner

Jul 18 '05 #9
harold fellermann wrote:
Hi,

I cannot see any strange behavior. this code works exacly as you and I
suspect:
>>> def otherfunction(x) : .... return x
.... >>> def function(arg=otherfunction(5)) : .... return arg
.... >>> function(3) 3 >>> function()

5

Or is this not what you excepted?


Channelling the effbot, I think he was asking what namespace context you
expected the expression "arg=otherfunction(x)" to be evaluated in when
it's used at the time of a function call to dynamically create a new
default value for arg.

regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #10
"harold fellermann" wrote:
I cannot see any strange behavior. this code works exacly as you and I suspect:


you seem to have missed some of the posts that led up to the one you
replied to. (most importantly, the first one).

</F>

Jul 18 '05 #11
br********@securetrading.com wrote:
However, is there a good reason why default parameters aren't evaluated
as the function is called? (apart from efficiency and backwards
compatibility)?


So, one of my really common use cases that takes advantage of the fact
that default parameters are evaluated at function definition time:

def foo(bar, baz, matcher=re.compile(r'...')):
...
text = matcher.sub(r'...', text)
...

If default parameters were evaluated when the function was called, my
regular expression would get re-compiled every time foo() was called.
This would be inefficient, especially if foo() got called a lot. If
Python 3000 changed the evaluation time of default parameters, I could
rewrite this code as:

class foo(object):
matcher=re.compile(r'...')
def __new__(self, bar, baz, matcher=None):
if matcher is None:
matcher = self.matcher
...
text = matcher.sub(r'...', text)
...

But that seems like a lot of work to do something that used to be pretty
simple...

Steve
Jul 18 '05 #12
> Channelling the effbot, I think he was asking what namespace context
you
expected the expression "arg=otherfunction(x)" to be evaluated in when it's used at the time of a function call to dynamically create a new
default value for arg.


Thanks, I realise now that's what was meant. I think I was just
assuming otherfunction() would be globally available - but that's not
something I want to go into since I can see now there will be problems
trying to define what python should do if it evaluated defaults at the
function call :)

I think I can now explain to someone why there are good reasons that
the default params are evaluated at the definition. However, I still
can't give a nice looking solution on how to re-write a function to
have empty mutable values as default arguments: eg.

def method(a,b,opt1=[],opt2=None,opt3="",opt4={})

How could I re-write this (especially if there are perhaps 20 optional
parameters,any number of which may have mutable defaults) without
writing 20 "if opt1 is None: opt1=[]" statements?

Brian

Jul 18 '05 #13

brian.b...@securetrading.com wrote:
Channelling the effbot, I think he was asking what namespace context
you
expected the expression "arg=otherfunction(x)" to be evaluated in when
it's used at the time of a function call to dynamically create a

new default value for arg.


Thanks, I realise now that's what was meant. I think I was just
assuming otherfunction() would be globally available - but that's not
something I want to go into since I can see now there will be

problems trying to define what python should do if it evaluated defaults at the function call :)

I think I can now explain to someone why there are good reasons that
the default params are evaluated at the definition. However, I still
can't give a nice looking solution on how to re-write a function to
have empty mutable values as default arguments: eg.

def method(a,b,opt1=[],opt2=None,opt3="",opt4={})

How could I re-write this (especially if there are perhaps 20 optional parameters,any number of which may have mutable defaults) without
writing 20 "if opt1 is None: opt1=[]" statements?

Brian


One way that is *slightly neater* is to simply collect all keyword
arguments as a dictionary. Then compare with a dictionary of defaults
for any missing keywords.

def afunction(**keywargs):
defaults = {'param1' : [], 'param2' : {}, 'param3' : []}
for entry in defaults:
if not keywargs.has_key(entry):
keywargs[entry] = defaults[entry]

This keeps all your defaults in a single dictionary and avoids a really
long function definition.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

Jul 18 '05 #14

brian.b...@securetrading.com wrote:
Channelling the effbot, I think he was asking what namespace context
you
expected the expression "arg=otherfunction(x)" to be evaluated in when
it's used at the time of a function call to dynamically create a

new default value for arg.


Thanks, I realise now that's what was meant. I think I was just
assuming otherfunction() would be globally available - but that's not
something I want to go into since I can see now there will be

problems trying to define what python should do if it evaluated defaults at the function call :)

I think I can now explain to someone why there are good reasons that
the default params are evaluated at the definition. However, I still
can't give a nice looking solution on how to re-write a function to
have empty mutable values as default arguments: eg.

def method(a,b,opt1=[],opt2=None,opt3="",opt4={})

How could I re-write this (especially if there are perhaps 20 optional parameters,any number of which may have mutable defaults) without
writing 20 "if opt1 is None: opt1=[]" statements?

Brian


One way that is *slightly neater* is to simply collect all keyword
arguments as a dictionary. Then compare with a dictionary of defaults
for any missing keywords.

def afunction(**keywargs):
defaults = {'param1' : [], 'param2' : {}, 'param3' : []}
for entry in defaults:
if not keywargs.has_key(entry):
keywargs[entry] = defaults[entry]

This keeps all your defaults in a single dictionary and avoids a really
long function definition.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

Jul 18 '05 #15

Steven Bethard wrote:
br********@securetrading.com wrote:
However, is there a good reason why default parameters aren't evaluated as the function is called? (apart from efficiency and backwards
compatibility)?
So, one of my really common use cases that takes advantage of the

fact that default parameters are evaluated at function definition time:

def foo(bar, baz, matcher=re.compile(r'...')):
...
text = matcher.sub(r'...', text)
...

Surely "re.compile(r'...')" is effectively a constant ? So your above
code is equivalent to :

aConst = re.compile(r'...')
def foo(bar, baz, matcher=aConst):
....
text = matcher.sub(r'...', text)
....

I agree that dynamic evaluation of default arguments seems much more
pythonic, as well as getting rid of a common python gotcha.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shmtl
If default parameters were evaluated when the function was called, my regular expression would get re-compiled every time foo() was called. This would be inefficient, especially if foo() got called a lot. If
Python 3000 changed the evaluation time of default parameters, I could rewrite this code as:

class foo(object):
matcher=re.compile(r'...')
def __new__(self, bar, baz, matcher=None):
if matcher is None:
matcher = self.matcher
...
text = matcher.sub(r'...', text)
...

But that seems like a lot of work to do something that used to be pretty simple...

Steve


Jul 18 '05 #16
Fuzzyman wrote:
Steven Bethard wrote:
br********@securetrading.com wrote:
However, is there a good reason why default parameters aren't
evaluated as the function is called? (apart from efficiency
and backwards compatibility)?


So, one of my really common use cases that takes advantage of the
fact that default parameters are evaluated at function definition
time:

def foo(bar, baz, matcher=re.compile(r'...')):
...
text = matcher.sub(r'...', text)
...


Surely "re.compile(r'...')" is effectively a constant ? So your above
code is equivalent to :

aConst = re.compile(r'...')
def foo(bar, baz, matcher=aConst):
...
text = matcher.sub(r'...', text)
...


Basically, yes. Though you add an extra name to the module or class
namespace by defining 'aConst'. I consider this a minor pollution of
the namespace since 'matcher' is only used in the function, not the
module or class.

But if we're arguing for equivalencies, the oft-asked for

def foo(lst=[]):
...

where [] is evaluated for each function call, is equivalent for most
purposes to:

def foo(lst=None):
if lst is None:
lst = []

There's a minor pollution of the range of values 'lst' can take on -- if
you need lst to be able to take on the value None, you'll want to
rewrite this something like:

no_value = object()
def foo(lst=no_value):
if lst is no_value:
lst = []

My point here is that there's always going to be some equivalent
expression (turing completeness etc.) I was just pointing out a quite
reasonable use of the current default parameter evaluation system.

Steve
Jul 18 '05 #17

Steven Bethard wrote:
Fuzzyman wrote:
Steven Bethard wrote:
br********@securetrading.com wrote:

However, is there a good reason why default parameters aren't
evaluated as the function is called? (apart from efficiency
and backwards compatibility)?

So, one of my really common use cases that takes advantage of the
fact that default parameters are evaluated at function definition
time:

def foo(bar, baz, matcher=re.compile(r'...')):
...
text = matcher.sub(r'...', text)
...
Surely "re.compile(r'...')" is effectively a constant ? So your above code is equivalent to :

aConst = re.compile(r'...')
def foo(bar, baz, matcher=aConst):
...
text = matcher.sub(r'...', text)
...


Basically, yes. Though you add an extra name to the module or class
namespace by defining 'aConst'. I consider this a minor pollution of

the namespace since 'matcher' is only used in the function, not the
module or class.

But if we're arguing for equivalencies, the oft-asked for

def foo(lst=[]):
...

where [] is evaluated for each function call, is equivalent for most
purposes to:

def foo(lst=None):
if lst is None:
lst = []

There's a minor pollution of the range of values 'lst' can take on -- if you need lst to be able to take on the value None, you'll want to
rewrite this something like:

no_value = object()
def foo(lst=no_value):
if lst is no_value:
lst = []

My point here is that there's always going to be some equivalent
expression (turing completeness etc.) I was just pointing out a quite reasonable use of the current default parameter evaluation system.

Steve


Sure.. but you also gave an example of an alternative that was complex,
and used it's complexity as an argument against having default
arguments dynamically evaluated. What I was saying is that there is an
alternative that is at least as readable (if not more) than your
example.

Having default arguments evaluated when the function is defined is
unintuitive and unpythonic.
Regards,
Fuzzy
http://www.voidspace.org.uk/python/index.shtml

Jul 18 '05 #18
Fuzzyman wrote:

[...]

Having default arguments evaluated when the function is defined is
unintuitive and unpythonic.


With due respect that's a matter of opinion.

Having default arguments evaluated when the function is defined is the
result of several design decisions in Python, not the least of which is
the decision to have "def" be an executable statement. Ever wondered how
come you can def the same function name several times in the same
module? It's simply because on of def's side-effects is the binding of
its name in the current namespace.

Unfortunately there's absolutely no guarantee that the namespace context
when a function is called will bear any relation to the namespace
context when it was defined (particularly given that definition and call
can take place in entirely separate modules). So, how would one specify
a "deferred expression" to be evaluated when the function is called
rather than when it is defined? There presumably has to be some
technique that's different from the current ones, since presumably you
would also want to retain the option of having the default evaluated at
definition time.

I still haven't seen any reasonable suggestions as to how one might
exactly specify the execution context for such a deferred expression,
let alone how to spell the deferred expression itself. Would you have us
provide a code object that can be eval()'d?

regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #19
Fuzzyman wrote:
Steven Bethard wrote:

So, one of my really common use cases that takes advantage of the
fact that default parameters are evaluated at function definition
time:

def foo(bar, baz, matcher=re.compile(r'...')):
...
text = matcher.sub(r'...', text)
...

Sure.. but you also gave an example of an alternative that was complex,


Interesting. I would have thought that my example was pretty simple.
Maybe it would be helpful to generalize it to:

def foo(bar, baz, spam=badger(x, y, z)):
...

All it does is use a default value that was produced by a function call.
I'm surprised you haven't run into this situation before...

Of course, what is complex or simple is a matter of personal opinion. I
use this pattern so often that it's quite simple to me, but I guess I
can understand that if you don't use such a pattern, it might seem
foreign to you.

Steve
Jul 18 '05 #20

Steven Bethard wrote:
Fuzzyman wrote:
Steven Bethard wrote:
>
>So, one of my really common use cases that takes advantage of the
>fact that default parameters are evaluated at function definition
>time:
>
>def foo(bar, baz, matcher=re.compile(r'...')):
> ...
> text = matcher.sub(r'...', text)
> ... Sure.. but you also gave an example of an alternative that was complex,
Interesting. I would have thought that my example was pretty simple. Maybe it would be helpful to generalize it to:

def foo(bar, baz, spam=badger(x, y, z)):
...

All it does is use a default value that was produced by a function call. I'm surprised you haven't run into this situation before...

Of course, what is complex or simple is a matter of personal opinion. I use this pattern so often that it's quite simple to me, but I guess I can understand that if you don't use such a pattern, it might seem
foreign to you.

Steve

Hello Steve,

It wasn't that part of the example that I thought was over complex.
(although it's not a 'pattern' I use often). You suggested that if we
had dynamic evaluation of default values, you would have to replace it
with :
class foo(object):
matcher=re.compile(r'...')
def __new__(self, bar, baz, matcher=None):
if matcher is None:
matcher = self.matcher
...
text = matcher.sub(r'...', text)
...


Now that I thought was over complex... when all you wanted to do was
put a constant into your default value !

Having said that I see Steve's point about not knowing the namespace
when the function will be called.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

Jul 18 '05 #21
<br********@securetrading.com> wrote:
...
I'm really looking for a neat way to do the following:

def method(a,b,opt1=None,opt2=None,opt3="",opt4=None):
if opt1 is None: opt1=[]
if opt2 is None: opt2={}
if opt4 is None: opt4=[]

Python syntax is normally so neat but this just looks a mess if there
are lots of parameters.


There's a decorator for that in the Cookbook (sorry, don't recall the
recipe number, but, it's on the site, and it got into the 2nd edition
which we're still expecting to have on paper at PyCon) -- basically
wrapping a function with a wrapper that does a copy.deepcopy on the
defaults values at each call (efficiency of course goes down the drain,
but you _did_ say "apart from efficiency"!-).
Alex
Jul 18 '05 #22
<br********@securetrading.com> wrote:
...
the default params are evaluated at the definition. However, I still
can't give a nice looking solution on how to re-write a function to
have empty mutable values as default arguments: eg.

def method(a,b,opt1=[],opt2=None,opt3="",opt4={})

How could I re-write this (especially if there are perhaps 20 optional
parameters,any number of which may have mutable defaults) without
writing 20 "if opt1 is None: opt1=[]" statements?


I don't have the recipe I mentioned at hand, but what about:

def makebrianhappy(f):
saved_defaults = f.func_defaults
def with_fresh_defaults(*a, **k):
f.func_defaults = copy.deepcopy(saved_defaults)
return f(*a, **k)
with_fresh_defaults.__name__ = f.__name__
return with_fresh_defaults

@ makebrianhappy
def method(a, b, opt1=[], opt2=None, opt3="", opt4={}):
...

I've added spaces after commas to make ME happy too (lack of such spaces
is my least favourite Python irritation;-), but I guess the semantics of
this (UNTESTED) code would work even without that;-).
Alex
Jul 18 '05 #23
Fuzzyman wrote:
It wasn't that part of the example that I thought was over complex.
(although it's not a 'pattern' I use often). You suggested that if we
had dynamic evaluation of default values, you would have to replace it
with :
>class foo(object):
> matcher=re.compile(r'...')
> def __new__(self, bar, baz, matcher=None):
> if matcher is None:
> matcher = self.matcher
> ...
> text = matcher.sub(r'...', text)
> ...

Now that I thought was over complex... when all you wanted to do was
put a constant into your default value !


Ahh. Yeah, the thing above is a bit complex, but it keeps the same
namespaces -- matcher is only available to foo, not the enclosing
class/module. Point taken of course. ;)

Steve
Jul 18 '05 #24
Thanks. In case anyone else is looking, the recipe is at:
http://aspn.activestate.com/ASPN/Coo.../Recipe/303440

(which also shows how to make it work with python2.3 and below since
they don't support decorators)

Brian

Jul 18 '05 #25

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

24 posts views Thread by Shao Zhang | last post: by
8 posts views Thread by matthewperpick | last post: by
10 posts views Thread by Armando Serrano Lombillo | last post: by
20 posts views Thread by Jasper | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.