[Python-Dev] PEP 329: Treating Builtins as Constants inthe Standard Library

Tim Delaney tcdelaney at optusnet.com.au
Mon Apr 19 11:56:41 EDT 2004

Phillip J. Eby wrote:

> At 08:54 AM 4/19/04 -0400, Raymond Hettinger wrote:
>> Comments are invited on a new pep:
>>         http://www.python.org/peps/pep-0329.html
> I'm not sure I understand the reasoning for implementing this via a
> bytecode hack, rather than in the compiler or loading mechanisms.  I
> think
> I'd rather see something like:
>     from __future__ import fast_globals

+1. The semantics would have to be that globals *may* be optimised when the
above is present (and code should assume that they will be) but there is no
guarantee i.e. code should work both in the presence and absence of the
above. This allows Jython (for example) to ignore it entirely, partially
implement it, or completely implement it as desired.

An additional bonus is that this puts it up front, so someone reading the
code knows that the author is expecting optimisations to occur - when it's
at the end it's much more likely to be missed, and also much less likely to
be taken into account when reading the code.

> which would mean that globals and builtins could be considered
> constants unless declared with 'global' at the module level.

This would be a backwards-incompatible change (and hence definitely
warranting the __future__) but I presume you mean considered constant within
the module that they are defined - hence essentially a non-issue.

> Then, the compiler
> could optimize any undeclared builtins, and the 'MAKE_FUNCTION' opcode
> could bind any constants defined as of the function's declaration.

I know it's been suggested before, but I believe the idea of module-level
locals - an indexed lookup rather than a dict lookup - might be worthwhile
considering as part of this. That would also give improved performance for
external modules using module-level names.

> Finally, the module object thus created would ban any __setattr__ on
> any constant that has been bound into a function.  (Since these are the
> only setattrs that could cause harm.)

It's late (2am), so I'm not entirely sure I understand this - do you mean
something like:

    class X:

    x = X()

    def func():
        print x

    x.a = 1

would throw an exception? Why would this cause a problem? The above would
become almost equivalent to:

    class X:

    x = X()

    def func():
        global x
        _x = x
        print _x

    x.a = 1

and I don't see a problem with that.

Tim Delaney

More information about the Python-Dev mailing list