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

Nick Coghlan ncoghlan at gmail.com
Mon Jun 20 16:56:34 CEST 2011


On Mon, Jun 20, 2011 at 4:26 AM, Terry Reedy <tjreedy at udel.edu> wrote:
> Did this not actually go through?

It did, I just forgot to reply. Sorry about that.

co_consts is not a namespace - it's just a cache where the compiler
stashes values (usually literals) that can be calculated at compile
time (note, NOT definition time - it happens earlier than that,
potentially even prior to the current application invocation if the
module was cached in a .pyc file).

Using it for mutable state is not possible, and thus would completely
miss the point of some of the significant uses of the default argument
hack. It is also quite possible for a single code object to be shared
amongst multiple function definitions (e.g. when a function
declaration is inside a loop). Accordingly, any new definition time
state needs to go on the function object, for all the same reasons
that current definition time state (i.e. annotations and default
parameter values) is stored there.

> I do not see what nonlocals has to do or needs to have to do with *local* constants. My proposal is that to store named constants, we reuse the current code to recognize and calculate named defaulted locals with the current code to store and retrieve anonymous constants,

The nonlocals handling code is relevant because creating state that is
shared between function invocations is what happens with closures, and
the nonlocal statement serves to tell the compiler that names that
would otherwise be considered local should instead be considered
closure references. We want the new statement to do something similar:
the nominated names will exist in the new definition time namespace
rather than being looked up in any of the existing locations (locals,
outer scopes, globals/builtins).

And, as noted above, the const calculation code isn't useful because
it happens at the wrong time (compilation time instead of definition
time) and because code objects may be shared amongst multiple function
definitions.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list