[Python-Dev] Re: native code compiler? (or, OCaml vs. Python)
Guido van Rossum
guido@python.org
Mon, 03 Feb 2003 16:16:13 -0500
> Guido> I was thinking of adding appropriate new opcodes for a few
> Guido> builtins that are called a lot, like len. This would be
> Guido> implemented using something like this:
>
> Guido> case BUILTIN_LEN:
> ...
>
> Would you special case those calls so that, in effect, __builtin__.len
> couldn't be overridden by a "len" object in the globals or locals?
No, I would only generate a BUILTIN_LEN opcode if there was no local
or global variable 'len'.
A few days ago I proposed a restriction on assigning to an attribute
of a module that stores a new name in that module that is the same as
the name of a built-in; that was meant to outlaw people doing ugly
stuff like
import random
random.len = lambda x: len(x)-1
print random.choice([1,2,3])
and expecting to affect the implementation of choice().
I don't think anybody would do this on purpose (or even by accident),
but the possibility exists, and I'd prefer to live without lying awake
about that case.
(We could make random.__dict__ read-only, like the new-style class
__dict__, if you worry about other ways of stuffing unexpected
variables inside it. We could also avoid the optimization if there's
an exec statement anywhere in a module, since one could exec code that
says
import __builtin__
global len
len = lambda x: __builtin__.len(x)-1
or one could find another way of outlawing such abominations
(including simply declaring that one shouldn't do that).
--Guido van Rossum (home page: http://www.python.org/~guido/)