Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #8480

Re: Default value for optional parameters unexpected behaviour?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Default value for optional parameters unexpected behaviour?
Date 2011-06-26 14:46 -0400
References <2a25a54a-c60b-4811-9c6a-97c7f717dccb@hd10g2000vbb.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.428.1309113996.1164.python-list@python.org> (permalink)

Show all headers | View raw


On 6/26/2011 2:28 PM, Marc Aymerich 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)?

Our fine Language Reference. Compound Statements chapter, Function 
definitions section, says in bold type: "Default parameter values are 
evaluated when the function definition is executed. ". I presume the 
tutorial says this somewhere too. Read both, along with the first 5 
chanpter of the Library reference.

If you want code executed when you call the function, put it in the body 
that is executed when you call the function

def f(lst = None):
   if lst is None:
     lst = []
     ...

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Default value for optional parameters unexpected behaviour? Marc Aymerich <glicerinu@gmail.com> - 2011-06-26 11:28 -0700
  Re: Default value for optional parameters unexpected behaviour? Shashank Singh <shashank.sunny.singh@gmail.com> - 2011-06-27 00:09 +0530
  Re: Default value for optional parameters unexpected behaviour? Corey Richardson <kb1pkl@aim.com> - 2011-06-26 14:36 -0400
  Re: Default value for optional parameters unexpected behaviour? Noah Hall <enalicho@gmail.com> - 2011-06-26 19:45 +0100
  Re: Default value for optional parameters unexpected behaviour? Terry Reedy <tjreedy@udel.edu> - 2011-06-26 14:46 -0400
  Re: Default value for optional parameters unexpected behaviour? Benjamin Kaplan <benjamin.kaplan@case.edu> - 2011-06-26 12:21 -0700
  Re: Default value for optional parameters unexpected behaviour? Corey Richardson <kb1pkl@aim.com> - 2011-06-26 15:23 -0400

csiph-web