ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-Tutor
python-Tutor
Re: [Tutor] Python function seem to have a memory ???
by dman other posts by this author
Aug 12 2001 10:36PM messages near this date
[Tutor] Python function seem to have a memory ??? | Re: [Tutor] Python function seem to have a memory ???
Others have already explained why it works the way it does, but
haven't given an example of how to get a default argument value of a
new empty list each time the function is called. 


On Sat, Aug 11, 2001 at 02:42:50PM -0100, Simon Vandemoortele wrote:

| --- quote ---
| Important warning: The default value is evaluated only once. This makes a 
| difference when the default is a mutable object such as a list or dictionary. 
| For example, the following function accumulates the arguments passed to it on 
| subsequent calls: 
| 
| def f(a, l = []):
|     l.append(a)
|     return l
| print f(1)
| print f(2)
| print f(3)
| 
| This will print 
| 
| [1]
| [1, 2]
| [1, 2, 3]
| --- end quote ---

Try 

def f( a , l = None ) ;
    if l is None :
        l = []
    l.append( a )
    return l


'None' is an immutable object.  This means it can't change and will
always be the same.  The first thing I do in the function is to see if
'l' has the default value.  If it does I create a new local binding to
a new empty list object called 'l'.  Then I proceed to modify it and
return it as before.  This idiom will have the desired effect.

HTH,
-D


_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Simon Vandemoortele
dman
Danny Yoo
Kalle Svensson
Danny Yoo
Lloyd Kvam

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved