don't understand behaviour of recursive structure

MRAB google at mrabarnett.plus.com
Sat Mar 14 19:54:20 CET 2009


bieffe62 at gmail.com wrote:
> On 14 Mar, 17:31, Dan Davison <davi... at stats.ox.ac.uk> wrote:
>> I'm new to python. Could someone please explain the following behaviour
>> of a recursive data structure?
>>
>> def new_node(id='', daughters=[]):
>>     return dict(id=id, daughters=daughters)
>>
> 
> Most probably, here is the problem : try this instead:
> 
> def new_node(id='', daughters=None):
>      if not daughters: daughters = []
>      return dict(id=id, daughters=daughters)
> 
> This is one of the less intuitive points in python: default values are
> evaluated only once,
> at 'compile' time I think. So when you call twice 'new_node' without
> specifying the daughters
> parameters, both dict will have the _same_  list.  Hence chaos
> 
[snip]
It's not really 'compile' time. 'def' is a _statement_, not a
declaration. Its effect is to create a function and bind it to a name in 
the current namespace. Any default parameters are evaluated when the
function is created and they are shared by all the function calls.



More information about the Python-list mailing list