[Python-Dev] Re: native code compiler? (or, OCaml vs. Python)
Guido van Rossum
guido@python.org
Mon, 03 Feb 2003 16:58:54 -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.
>
> do you mean specifically random.__dict__ or any modules dict?
Any module's dict.
> If the latter there would be quite some breakage. It is at least
> used for monkey patching modules to make them "unittestable" which
> is a valid use case IMO.
Why would this be done by patching the module's __dict__ rather than
assigning to attributes of the module?
> Maybe module's dicts could be "frozen" by default and this could be
> explicitely turned off (via a sys-hook).
What I proposed was only closing off write access to the __dict__ so
that the setattr code for type module can implement certain
restrictions (e.g. no assignment to attributes named "len").
--Guido van Rossum (home page: http://www.python.org/~guido/)