[Python-ideas] 'Injecting' objects as function-local constants
steve at pearwood.info
Sat Jun 18 06:03:34 CEST 2011
Nick Coghlan wrote:
> On Fri, Jun 17, 2011 at 10:12 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> You have missed a fourth option, which I have been championing: make inject
>> an ordinary function, available from the functools module. The
>> *implementation* of inject almost certainly will require support from the
>> compiler, but that doesn't mean the interface should!
> No, I didn't miss it, I left it out on purpose because I think messing
> with the runtime name lookup semantics is a terrible idea.
Isn't changing name lookup semantics at runtime precisely what JIT
compilers do? But it doesn't really matter, because that's not what I'm
proposing. I'm not suggesting that the lookup semantics should be
changed when the function is called. I'm saying that a new function
should be created, based on the original function, with the desired
In principle, this could be as simple as:
- make a copy of the function object
- in the copy, add cells for any injected variable
- and modify the copied code object to change the appropriate
LOAD_GLOBAL opcodes to LOAD_DEREF (and similarly for rebindings).
although I dare say that in practice there'll be a certain amount of
book-keeping required to make it work reliably.
More information about the Python-ideas