[Python-Dev] Re: native code compiler? (or, OCaml vs. Python) (original) (raw)

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 BUILTINLEN: > > ... > > > > 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 BUILTINLEN 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/)