On Tue, Dec 7, 2021 at 1:28 AM Steven D'Aprano <steve@pearwood.info> wrote:
On Tue, Dec 07, 2021 at 12:53:39AM +1100, Steven D'Aprano wrote:
If we can't execute the expression without the context existing, we make it exist. Details to follow in another post.
Here is some handwavy pseudo-code for setting up the context prior to calling a function "func":
code = func.__code__ locals = [NIL pointer for _ in range(code.co_nlocals)] cells = [cell() for _ in range(len(code.co_cellvars))] assign args, kwargs, early defaults to locals # make a frame frame = Frame() frame.f_back = current frame frame.f_lasti = 0 frame.f_locals = locals + cells + list(func.__closure__) frame.f_code = code
and then the interpreter does its funky thang with the frame and the function is executed.
But here's the thing... there is nothing that says that the f_code has to have come from func.__code__. It just needs to be code that expects the same environment (locals, cell, etc) as the frame is set up for.
Okay. So you want to break out a separate code object from the main body, but it has to expect the exact same environment as the main body. Which means you cannot replace it with anything else, you cannot call it externally without constructing the exact same environment, and frankly, I cannot for the life of me see what you gain above just having it part of the body. You keep arguing in favour of having it be somehow separate, but to what end? Please. Go make a reference implementation. At least then we'll know what's possible and what's not. ChrisA