[Python-ideas] 'Injecting' objects as function-local constants

Ronald Oussoren ronaldoussoren at mac.com
Fri Jun 17 16:30:00 CEST 2011





On 17 Jun, 2011, at 7:37, Steven D'Aprano wrote:

> Nick Coghlan wrote:
>> On Fri, Jun 17, 2011 at 3:15 AM, Jan Kaliszewski <zuo at chopin.edu.pl> wrote:
>>> or even (to stress that it is a language syntax construct:
>>> 
>>>   @inject mem=collections.Counter(), MAX_MEM=1000
>>>   def do_and_remember(val, verbose=False):
>> While that would require the from__future__ dance to make "inject" a
>> new keyword, I like it much better than the
>> looks-like-a-decorator-but-isn't syntax.
> 
> What benefit is there in making inject a keyword? Even super isn't a keyword.
> 
> As far as I'm concerned, inject need only be a function in the functools module, not even a built-in, let alone a keyword.
> 
> Here's a quick and dirty version that comes close to the spirit of inject, as I see it. Thanks to Alex Light's earlier version.

FYI <http://code.activestate.com/recipes/277940-decorator-for-bindingconstants-at-compile-time/> implements a "bind all globals" variant of the injection using byte-code hacks. Changing that to only bind specific globals should be easy enough ;-)

Is the inject functionality needed by other Python implementations, and in particular by PyPy?   I use the keyword arguments hack mostly for two reasons: slightly higher speed in tight loops and a workaround for accessing globals in __del__ methods. Both are primairily CPython hacks,  AFAIK the PyPy jit is smart enough to optimize globals access close to the speed of local variable acces.

A stdlib function that implements the activestate recipe would be good enough if the functionality is only needed for CPython (with a fallback to an function that doesn't change the function body for the other Python implementations)

Ronald



More information about the Python-ideas mailing list