functions, optional parameters

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun May 10 01:25:32 EDT 2015


On Sun, 10 May 2015 01:35 pm, Rustom Mody wrote:

> On Sunday, May 10, 2015 at 8:16:07 AM UTC+5:30, Steven D'Aprano wrote:
>> I predict that the majority of the time, late binding would just be a
>> pointless waste of time:
>> 
>> def process_string(thestr, start=0, end=None, slice=1, reverse=True):
>>     pass
>> 
>> Why would you want 0, None, 1 and True to be re-evaluated every time?
>> Admittedly it will be fast, but not as fast as evaluating them once, then
>> grabbing a static default value when needed. (See below for timings.)
>> 
> 
> And what is the work involved in (re)computing 0, None, 1, True??

Re-computing a constant is about 5 times more expensive than re-using it,
according to my earlier timing tests. So if you have four of them, there
will be about 20 times more overhead due to the defaults, each and every
time you call the function.

Setting the defaults isn't the only source of overhead, but my guestimate is
that switching to late binding would probably double the overall overhead
of calling a function with one or two defaults. If your function is
expensive, that's trivial, but for small fast functions, that will be
painful. Python's slow enough without making it slower for dubious gains.


> If I write (... arg=square_root_of_grahams_number())
> I would expect to pay for it.

Sure, but only once. If you think that Graham's Number is likely to change
*wink* then you can put it into the body of the function, like any other
code you want run every time you call the function.



-- 
Steven




More information about the Python-list mailing list