[Python-Dev] PEP 329: Treating Builtins as Constants in
the Standard Library
Phillip J. Eby
pje at telecommunity.com
Mon Apr 19 15:25:00 EDT 2004
At 02:37 PM 4/19/04 -0400, Nick Bastin wrote:
>You could, of course, create a statement like "const len" to flag that len
>will NOT be changed, thus creating true backwards compatibility, but you'd
>like to believe that const is the 95% use case, and thus it should be
>"volatile foo" when you want to change foo, but that's not all that
>backwards compatible.
For names that are never bound by a module's code (i.e. no 'foo=', 'import
foo', 'global foo'), it should be safe to make them "constant", since there
is nothing that can change them now except tinkering with the builtins, or
assigning them from outside modules. (The big hurdle here is 'from
somewhere import *' if 'somewhere' defines any names that shadow
builtins. Of course, one could simply say that using 'import *' disables
this optimization.)
I'm more cautious wrt module globals, however. As I've been thinking about
this today, I keep finding things that will not quite work as expected if
too many globals become "constants". Optimizing only builtins, however,
would probably give plenty of speed improvement, and not require anything
more complex than:
len = len
to re-enable substitution of a given builtin. But I think module objects
would need to change in a way that allows a loaded module to flag what
builtins are changeable, so that warnings could be generated during the
transition period.
IOW, module objects need to know what names they should reject for
__setattr__, and whether the rejection should be a warning or
error. Modules with 'from __future__ import fast_builtins' would generate
errors when other code tried to modify their builtins, and the rest would
issue warnings indicating that you must specifically enable that by
assigning to the builtin in the target module.
Hm. That means, by the way, that the compiler would need to detect these
issues and track modifiable builtins in *all* modules, not just those using
the future statement. But only the ones using the future statement would
be able to take advantage of faster access to builtins (or builtin
replacements like a "len" opcode, or compiler tricks to optimize away
builtins).
More information about the Python-Dev
mailing list