From: Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> 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 --- BBBS/Li6 v4.10 Toy-3 * Origin: Prism bbs (1:261/38) -- https://mail.python.org/mailman/listinfo/python-list