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 other posts by this author
Aug 12 2001 9:17PM messages near this date
RE: [Tutor] Windows, Python and me | [Tutor] source code
>  --- quote ---
>  Important warning: The default value is evaluated only once. 

This is the key statement

>  def f(a, l = []):
>      l.append(a)
>      return l

So the default is a reference to an empty list

>  print f(1)

and now we put a=1 into that list

>  print f(2)

and now a=2 goes in. its the same list because python 
only evaluates the default once when the function is defined.

This is rather like "closure" behaviour in other languages 
like perl or lisp. Indeed you can use this behaviour to make 
lambda functions more useful(you'll cover lambdas later ;-)


>  One thing I find astonishing about this is the fact that 
>  python functions seem to have memory; 

Correct, it remembers the default and, as it is mutable, 
the content changes. This can be useful when you want it 
and infuriating when you don't!

Alan G

_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor

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