Monday 15 July 2013

Python functions - Default values as function arguments

There is a slightly quirky thing(I think so, maybe other's don't) to note about Python functions if one has to  make one of the arguments as a default argument.
Remember this be heart:
Python default argument to a function are evaluated and stored only when the function is defined which, which happens only once.

So if you have a function as below:

def mygettime(curtime = time.time())
      print curtime

So everytime you call mygettime
>>mygettime()
>>mygettime()
>>mygettime()

expecting it to print different times , you are in for a surprise if you haven't got this cleared.

It prints same value (seconds since epoch time 1 Jan 1970 ) , giving you a notion that you have just stopped the time..
No you haven't.

What is happening then:
Python evaluates curtime = time.time() only once at the time function mygettime is defined 
which returns the time in seconds since the epoch and that value is what is stored and same value is printed in every call which was evaluated and stored only once.

There are different aspects to this behaviour depending upon whether the default argument is a mutable, or immutable python data type.






No comments: