Default value for optional parameters unexpected behaviour?

Thomas L. Shinnick tshinnic at prismnet.com
Sun Jun 26 14:53:21 EDT 2011


At 01:39 PM 6/26/2011, Shashank Singh wrote:
>On Sun, Jun 26, 2011 at 11:58 PM, Marc Aymerich <glicerinu at gmail.com> wrote:
> > Hi,
> > I'm trying to define a function that has an optional parameter which
> > should be an empty list whenever it isn't given. However, it takes as
> > value the same value as the last time the function was executed. What
> > is the reason of this behaviour? How does python deal with default
> > values (i.e. when are they assigned/created)?
>
>This has been discussed before in this list, quite a few times
>http://mail.python.org/pipermail/python-list/2010-March/1239044.html
>
>A solution is to accept default value as None assign to [] by checking
>for None inside the function
>
>def f(a=None):
>   if a is None: a = []

See reference manual section 7.6  "Function definitions" under the 
discussion subtitle "Default parameter values are evaluated when the 
function definition is executed. "
         http://docs.python.org/reference/compound_stmts.html#function-definitions

Yes, this is discussed in many places and many times, but why isn't 
it in the Python FAQ?  Amazing, yes?

>--
>Regards
>Shashank Singh
>http://rationalpie.wordpress.com
>--
>http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110626/8cd80f3a/attachment-0001.html>


More information about the Python-list mailing list