Early binding as an option

Chris Angelico rosuav at gmail.com
Wed Aug 3 00:08:48 CEST 2011


On Tue, Aug 2, 2011 at 9:23 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 8/2/2011 12:55 PM, Chris Angelico wrote:
>>
>> As I understand it, Python exclusively late-binds names; when you
>> define a function, nothing is ever pre-bound.
>
> By 'pre-bound' you presumably mean bound at definition time rather than call
> time. Default arg objects *are* pre-computed and pre-bound to internal slots
> at definition time.

Of course; that's a different issue altogether. No, I'm talking about
the way a tight loop will involve repeated lookups for the same name.

Unfortunately, there is no way - by definition - to guarantee that a
binding won't change. Even in the example of getting the lengths of
lines in a file, it's entirely possible for __len__ to rebind the
global name "len" - so you can't rely on the repeated callings of
len() to be calling the same function.

But who WOULD do that? It's somewhat ridiculous to consider, and
there's a huge amount of code out there that does these repeated calls
and does not do stupid rebindings in the middle. So Python permits
crazy behaviour at the cost of the performance of normal behaviour.

With the local-variable-snapshot technique ("len = len"), can anything
be optimized, since the parser can guarantee that nothing ever
reassigns to it? If not, perhaps this would be a place where something
might be implemented:

@const(len,max) # maybe this
def maxline(f):
   @const len,max # or this
   n = 0
   for line in somefile:
       n = max(n,len(line))
   return n

Some notation like this could tell the interpreter, "I don't expect
'len' or 'max' to be rebound during the execution of this function.
You're free to produce wrong results if either is."

So... Would this potentially produce wrong results? Would it be of any
use, or would its benefit be only valued in times when the whole
function needs to be redone in C?

Chris Angelico



More information about the Python-list mailing list