Default parameters
Carl Banks
imbosol at aerojockey.invalid
Fri Dec 19 20:43:00 EST 2003
Paul Rubin wrote:
>
>
> Carl Banks <imbosol at aerojockey.invalid> writes:
>> Consider something like this:
>>
>> def func(param=((1,2),(3,4),(5,6),(7,8))):
>> whatever
>>
>> Do you really want to be building a big-ass nested tuple every time
>> the function is called?
>
> Come on, the compiler can easily recognize that that list is constant.
Yes, but that doesn't account for all expensive parameters. What
about this:
DEFAULT_LIST = ((1,2),(3,4),(5,6),(7,8))
def func(param=DEFAULT_LIST):
pass
Or this:
import external_module
def func(param=external_modules.create_constant_object()):
pass
Or how about this:
def func(param={'1': 'A', '2': 'B', '3': 'C', '4': 'D'}):
pass
The compiler couldn't optimize any of the above cases.
>> Python evaluates default args at time of definition mostly for
>> performance reasons (and maybe so we could simulate closures before we
>> had real closures). My gut feeling is, moving the evaluation to call
>> time would be too much of a performance hit to justify it.
>
> Python takes so many other performance hits for the sake of
> convenience and/or clarity that this particular one would be miniscule
> by comparison.
Well, I don't have any data, but my gut feeling is this would be
somewhat more than "miniscule" performance hit. Seeing how pervasive
default arguments are, I'm guessing it would be a very significant
slowdown if default arguments had to be evaluated every call.
But since I have no numbers, I won't say anything more about it.
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
More information about the Python-list
mailing list