lambda in list comprehension acting funny

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jul 15 10:32:47 CEST 2012


On Sun, 15 Jul 2012 10:49:48 +1000, Chris Angelico wrote:

> On Sun, Jul 15, 2012 at 9:29 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Not necessarily *compile* time, but the distinction is between when the
>> function is defined (which may at compile time, or it may be at run
>> time) versus when the function is called.
> 
> I'd treat the def/lambda statement as "compile time" and the () operator
> as "run time".

But function definitions occur at run time, not compile time -- they are 
executable statements, not instructions to the compiler to define a 
function.

For example:

py> dis("def f(x): return x+1")  # Python 3.2
  1           0 LOAD_CONST               0 (<code object f at 0xb7b57de0,
                                            file "<dis>", line 1>)
              3 MAKE_FUNCTION            0
              6 STORE_NAME               0 (f)
              9 LOAD_CONST               1 (None)
             12 RETURN_VALUE

The code object is pre-compiled at compile time, but the function and 
name-binding (the "def") doesn't occur until runtime.

At compile time, Python parses the source code and turns it into byte-
code. Class and function definitions are executed at run time, the same 
as any other statement.

I'm not sure if this is a difference that makes a difference or not; I 
think it is, but don't know enough about how closures and scoping rules 
work in other languages to be sure that it does make a difference.


-- 
Steven



More information about the Python-list mailing list