[Python-ideas] Preallocated tuples and dicts for function calls
benrudiak at gmail.com
Sun Mar 10 15:08:36 EDT 2019
On Fri, Mar 8, 2019 at 6:23 PM Steven D'Aprano <steve at pearwood.info> wrote:
> A sets the argument tuple to (1, 2)
> B sets the argument tuple to (2, 3)
> B calls spam()
> A calls spam() # Oops!
I'm pretty sure the idea was to have constant tuples (1, 2) and (3, 4)
in the module instead of LOAD_CONST 1/2/3/4 instructions in the
bytecode. There's no setting of a hidden global variable involved.
The kwargs dicts are a harder problem. I suppose they would have to be
copy-on-write which would add too much complexity, or the language
would have to be changed to allow/require kwargs to be a frozendict.
> And then the pre-
> allocated tuples and dicts would hang around forever, wasting memory.
> Even if it turns out that the function never actually gets called:
> for x in sequence:
> if condition(x): # always returns False!
> the compiler will have pre-allocated the memory to call it.
The bytecode for "function(...)" already hangs around forever even if
it's never run.
There is no need for tuple constants because you can generate
LOAD_CONST a; LOAD_CONST b; ...; BUILD_TUPLE n at each usage point
instead, but CPython has tuple constants, so they must have some space
and/or speed benefit that was considered significant enough to be
worth implementing them. It seems like args constants for function
calls can be justified on similar grounds.
More information about the Python-ideas