better lambda support in the future?
tjreedy at udel.edu
Sat Dec 18 08:51:34 CET 2004
"Dima Dorfman" <dima at trit.invalid> wrote in message
news:slrncs76sg.1rvi.dima at beaver.trit.org...
> Both languages compile all three functions (f and the two versions of
> g) once and choose which g to return at run-time.
*If* OCaml or any other 'other' language compiles the two versions of g to
the final and complete functions that get returned (but I don't know if
that is so for OCaml or and other appropriate 'other'), then it does
something different from and less flexible than Python.
> You can see this in Python by examining the code object for f:
> >>> f.func_code.co_consts
> (None, 0, <code object g at 1c8120, file "<stdin>", line 3>,
> <code object g at 1cd1a0, file "<stdin>", line 6>)
It is important that these are code objects, not function objects.
> The last two elements are the variants of g. At run-time, one of them
> is loaded, made into a real function, and returned. All defs and
> lambdas are compiled only once when the module is loaded even if they
> depend on the environment or are referenced dynamically.
This is a CPython optimization which, I believe, is not part of the
language def itself -- but any sensible computer implementation should do
something like it.
The final wrapping of the code object by a function object must be done at
runtime because the defaulf arg evaluation and enclosing variable capture
happen on each call of the outer function and because each call therefore
returns a different function object -- though each uses the same code
object (or, in the case discussed, one of the same two code objects).
Terry J. Reedy
More information about the Python-list