optimization

Robert Kern robert.kern at gmail.com
Tue Dec 2 16:11:15 EST 2008


Neal Becker wrote:
> Robert Kern wrote:
> 
>> Neal Becker wrote:
>>> Arnaud Delobelle wrote:
>>>
>>>> Neal Becker <ndbecker2 at gmail.com> writes:
>>>>
>>>>> I noticed in some profiling, that it seems that:
>>>>>
>>>>> def Func ():
>>>>>   def something():
>>>>>     ...
>>>>>
>>>>> It appears that if Func is called many times, this nested func
>>>>> definition will cause significant overhead.  Is this true?  I guess
>>>>> I've become accustomed to decent compilers performing reasonable
>>>>> transformations and so have tended to write code for clarity.
>>>> If something() can be defined outside Func(), how is it clearer to
>>>> define it inside?
>>> If it's only used inside.
>> I, for one, find that significantly less clear. I only expect functions to
>> be defined inside of functions if they are going to use lexical scoping
>> for some reason. If I read your code, I'd probably waste a good five
>> minutes trying to figure out what part of the local scope you were using
>> before I would conclude that you just did it because you thought it looked
>> better.
> 
> I'm using the inner function to prevent pollution of the global namespace.  Local variables also have this attribute.  Code is easier to understand when it is written with the greatest locality - so you can see immediately that the inner function isn't used somewhere else.

I don't think that the greatest locality metric is the only factor in 
understandability. You're introducing more nesting, which means more context 
switching as I read the code. I like shortish functions with one coherent idea 
per function. I like to see the argument spec, the docstring, and the body of 
the code all on one page. If the functions it calls are reasonably well-named, 
or their calls are commented, I can read that function all the way through 
without having to page around. By nesting the definitions of the functions 
inside, I have to skip from the argument spec and docstring down to the body.

And I'm still going to spend time trying to figure out what lexical scoping you 
are using before giving up. I still think that defining a function inside of a 
function for organizational purposes is a (mild) abuse of the feature. Packages, 
modules, __all__, and the _underscoring conventions are the language features 
for organizing namespaces of functions.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list