Bug with [] as default value in functions? - bug.py (0/1)
Steve Holden
sholden at holdenweb.com
Thu Apr 12 09:04:56 EDT 2001
"Dinu Gherman" <dinu at reportlab.com> wrote in message
news:3ad5904d.176672030 at news.t-online.de...
> Hi,
>
> I noticed a very strange behaviour: I've got a recursive function like
> this:
>
> foo(spam, eggs=[]):
> ...
> return foo(spam, eggs=eggs
>
> where the default argument for eggs, the empty list, is *empty* for
> the top-level call only when it is explicitly provided with the func-
> tion call like this:
>
> bar = foo(mySpam, eggs=[])
>
> I've attached a more lengthy example showing, I hope, rather pre-
> cisely what I mean.
>
> Is this a bug or just a lack of understanding of recursion and name
> spaces, delicate as they are, in my brain??
>
I found no attachment. However, you should be aware that the default value
is bound to "eggs" at the time of function declaration. Furthermore, it is
mutable. If you modify eggs inside the function (as I presume you do before
your recursive call) you will see that modified value as the default the
next time you make a top-level call.
If, however, you provide an explicit value for eggs at the top level, the
default value will not be used.
Do you ever make a call to foo without explicitly providing a value for
eggs? If not there would seem little point in defining a default value.
Does this help?
regards
Steve
More information about the Python-list
mailing list