Proposal: Magic Constants

Oren Tirosh oren-py-l at hishome.net
Thu Aug 28 02:55:14 EDT 2003


If these values are to be treated as literals rather than funky function
calls they should be evaluated at module load time not when encountered 
during execution. Each literal should be evaluated only once regardless 
of the number of places it is referenced or how many times the code is 
executed.  Any bad literals inside a function should be detected 
even if the function is never called. 

Here's how it might work:

The compiler finds all custom literals in the module, merging identical
ones and puts them somewhere in the marshalled code object for the 
module. At the top nesting level of the module, before any reference to 
the custom literals (but possibly after some imports and assignments) the 
compiler places a call to the literal initialization code. This call 
will evaluate all custom literals and put them into a tuple of literals 
in the module namespace. The module code object and all its nested code 
objects (functions, class definitions, etc) index into this tuple when
referring to custom literals. Alternatively, these literals can actually
be loaded into the co_consts of the code objects and referenced with the
LOAD_CONST opcode like any other literal.

The effect is NOT global across all modules. Namespace conflicts must be 
resolved locally and explicitly (using Bernhard Herzog's idea of 
__literals__ = {...} or something similar).

All modules get an initial literals list that contains 'i'.  The code for 
complex numbers can then be removed from the interpreter and placed in an
extension module that is imported on demand. The default literals list 
might be changed globally in site.py but that would be at your own peril.

   Oren





More information about the Python-list mailing list