pootle
Posts: 351
Joined: Wed Sep 04, 2013 10:20 am
Location: Staffordshire
Contact: Website

function call as a parameter default only gets called once

Mon Feb 29, 2016 8:53 am

Just a behaviour I find slightly strange. An explanation of why the language behaves this way could be enlightening.

I made the default value of a parameter in a function definition a function call. I find in practice that this only gets evaluated the first time the function is called, so ended up defaulting to None with a test and call in the code.
def nicetimeinterval(timethen, timenow=time.time())
diff = int(timenow-timethen
......
:
This results in time.time() only being called once, with all subsequent calls picking up the value from the first call. Clearly not what I was expecting!

This is with Python 3

User avatar
joan
Posts: 14593
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: function call as a parameter default only gets called on

Mon Feb 29, 2016 9:22 am

That is documented behaviour. At least I remember reading about it when I was checking on default parameters.

User avatar
RogerW
Posts: 286
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

Re: function call as a parameter default only gets called on

Mon Feb 29, 2016 9:42 am

Yes (to my surprise) it is documented. This is from the 3.4.3 documentation.
Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified.

pootle
Posts: 351
Joined: Wed Sep 04, 2013 10:20 am
Location: Staffordshire
Contact: Website

Re: function call as a parameter default only gets called on

Mon Feb 29, 2016 12:24 pm

Aha, thanks very much. not what (was to me at least) the intuitive answer, but if that's what it says on the tin!...

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: function call as a parameter default only gets called on

Mon Feb 29, 2016 12:29 pm

The way this is typically dealt with (in my experience at least) is to have a default value of None and then, in the method itself, test if the parameter is None and then set the default variable at that stage.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Return to “Python”