[Tutor] lexical scoping efficiency

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Tue Nov 21 23:14:57 CET 2006


Alan Gauld schreef:
> "Matthew Gordon" <mrgordon at mit.edu> wrote
> 
>> Defining functions inside of other functions ...In terms
>> of efficiency though, it seems terrible to lexically scope because
>> each time the function is called it will have to reinstantiate the
>> sub-function.
> 
> I'm speaking from a position of profound ignorance however I'd be 
> surprised if Python does that.
> 
> I suspect that when Python first parses the function definition 
> it will create a cached reference to the nested function, probably 
> via a dictionary. Python is usually pretty good at creating cached 
> references to things that don't change and unlike local variables 
> the function definition will be the same for each invocation of the 
> function (although there is a possibility of some clever closure 
> behaviour rendering that invalid, but I don't think so)
> 
> But I'm guessing, does anyone else know for sure?

In a recent thread on comp.lang.python Fredrik Lundh said 
(http://groups.google.com/group/comp.lang.python/msg/81462fcf73104d8c):

"(yes, an inner function is *created* every time you execute the outer
function.  but it's created from prefabricated parts, so that's not a
very expensive process)."

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Tutor mailing list