Speed of Nested Functions & Lambda Expressions
Gary Herron
gherron at islandtraining.com
Tue Oct 23 12:06:20 EDT 2007
beginner wrote:
> Hi All,
>
> It is really convenient to use nested functions and lambda
> expressions. What I'd like to know is if Python compiles fn_inner()
> only once and change the binding of v every time fn_outer() is called
> or if Python compile and generate a new function object every time. If
> it is the latter, will there be a huge performance hit? Would someone
> give some hint about how exactly Python does this internally?
>
> def fn_outer(v):
> a=v*2
> def fn_inner():
> print "V:%d,%d" % (v,a)
>
> fn_inner()
>
> Thanks,
> Geoffrey
>
>
The code is compiled only once when the file is initially read in.
During execution of fn_outer, v will be bound to a value, then a, then
fn_inner will be bound (to an already compiled code object) and so on.
Really, from the point of view of Python while executing fn_outer, the
def of fn_inner looks just like an assignment with fn_inner as the
variable name and a code object as the value.
Gary Herron
More information about the Python-list
mailing list