Static variables [was Re: syntax difference]

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 23 22:41:36 EDT 2018


On Sun, 24 Jun 2018 00:37:36 +0100, Bart wrote:

> Do you mean that if the same 'def' block is re-executed, it will create
> a different instance of the function? (Same byte-code, but a different
> set of everything else the function uses.)

That's not as slow as you think it is. Everything that can be is pre-
prepared and assembling them is pretty fast:

py> import dis
py> dis.dis(lambda x: lambda n: x*n)
  1           0 LOAD_CLOSURE             0 (x)
              3 BUILD_TUPLE              1
              6 LOAD_CONST               1 (<code object <lambda> at
                                            0xb78b6430, file "<stdin>",
                                            line 1>)
              9 LOAD_CONST               2 ('<lambda>.<locals>.<lambda>')
             12 MAKE_CLOSURE             0
             15 RETURN_VALUE


How else can you get functions where the definition is not known until 
runtime, unless you assemble them at runtime?


> Wow. (Just think of all the times you write a function containing a neat
> bunch of local functions, every time it's called it has to create a new
> function instances for each of those functions, even if they are not
> used.)


That's why Pascal-style static nested functions are hardly ever used in 
Python. 99% of nested functions are closures.




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list