Early binding as an option

Thomas Jollans t at jollybox.de
Tue Aug 2 13:18:20 EDT 2011


On 02/08/11 18:55, Chris Angelico wrote:
> As I understand it, Python exclusively late-binds names; when you
> define a function, nothing is ever pre-bound. This allows a huge
> amount of flexibility (letting you "reach into" someone else's
> function and change its behaviour), but it's flexibility that most
> programs use seldom if at all.
> 
> First off: Is there any way to request/cause some names to be bound
> early? and secondly, should there be?
> 
> Argument against: Late binding is a Good Thing, and having some things
> bound early would be confusing.

Also, simplicity is a good thing, and Pytho name binding and scoping is
very simple.

> 
> Argument in favour: Efficiency is also a Good Thing, and with staples
> like 'len', it's unlikely anyone will want to change them - yet the
> interpreter still has to do a namespace lookup every time.
> 
> I would want the end programmer to have the ultimate power here (not
> the module designer). Something along the lines of: This global name
> will never change, so don't bother looking it up every time.

What you can do, as a module author, is bind builtins/globals as default
function arguments, making them local variables.

def uses_len (arg0, len=len):
    # you could probably write a decorator that strips away this kind of
    # "builtin" argument

As the module user, there's no way AFAIK. However, is this really
useful? I suppose it would be possible to introduce a kind of "constant
globals" namespace that a JIT compiler could then use to optimise, but
how much would this help? If the content of this namespace is unknown at
the time the module is compiled (and it would be), then only a JIT
compiler could use the information - which doesn't mean it couldn't
improve performance significantly in some cases. More importantly, how
can the module user know which globals should be declared constant? Only
the module author can know which names are looked up often enough for
optimisation to make sense, or even which names are looked up at all.

I think this effect can only, and best, be achieved in Python by binding
relevant globals as locals in the module, and documenting which these
are for the benefit of users who might want to change builtins, and
would have to do it before importing the module.

Thomas

> 
> As an example of this difference, Pike uses early binding for some
> things; when I did the perfect numbers testing in the other thread
> (discussion thread, not thread of execution!), Pike performed
> significantly better; I believe this is in part due to the formal
> declarations of variables, and the consequential simplification of
> local code, although since there are no globals being looked up here,
> there's little to be gained from those.
> 
> Is this the realm of JIT compilation, or can it be done in regular CPython?
> 
> Chris Angelico




More information about the Python-list mailing list