[Tutor] functions and default argument

Steven D'Aprano steve at pearwood.info
Fri Oct 21 19:25:51 CEST 2011


Praveen Singh wrote:
> In function-
> 
> "Default value is *evaluated only once*.This makes different when the
> default is a mutable object such as a list, dictionary or instance of most
> classes."
> 
> I am not getting it properly-evaluated once?? different behaviour???--
> please explain this.


Look at an example:


 >>> import time
 >>> def test(t=time.asctime()):
...     print t, "***", time.asctime()
...
 >>> time.sleep(30)  # wait a little bit
 >>> test()
Sat Oct 22 04:17:08 2011 *** Sat Oct 22 04:17:57 2011
 >>> time.sleep(30)  # wait a little bit longer
 >>> test()
Sat Oct 22 04:17:08 2011 *** Sat Oct 22 04:18:46 2011


Notice that the first time printed, using the default value, is the 
same. The default value for t is assigned once, and not calculated 
again. Since t is a string, it is immutable and can never change.

The same thing occurs when you use a mutable object like a list or a 
dict. The default value is assigned once, and once only. But notice that 
you can modify the default value, say by appending to it:


 >>> def test(x=[]):
...     print x, id(x)
...     x.append(1)
...
 >>> test()
[] 3085600236L
 >>> test()
[1] 3085600236L
 >>> test()
[1, 1] 3085600236L


It is the same default list every time, but the *contents* of the list 
are changing.



-- 
Steven


More information about the Tutor mailing list