Question about math.pi is mutable

BartC bc at freeuk.com
Sun Nov 8 12:54:57 EST 2015


On 08/11/2015 15:59, Michael Torrie wrote:
> On 11/08/2015 04:19 AM, BartC wrote:
>
>>> That elegant dynamism comes at a cost: method lookup is not a constant
>>> memory offset. Rather, it is a dictionary lookup.
>>
>> I've never understood why this seems to be necessary in Python. Why do
>> names have to be looked up? (I'm assuming this is searching by name in
>> some sort of table.)
>>
>> When a module is compiled, while the compiler can't see the definitions
>> inside the imported modules, it /will/ know all the names that appear in
>> this module, so it can organise them into fixed tables. Then the names
>> can be referred to by index. (I think LOAD_FAST does this.)
>>
>> Or is eval() the culprit here by making most optimisations impossible?
>
> Perhaps I'm misunderstanding what you're saying, here, but the reason a
> lookup has to be performed is because python variables are not like C
> variables. They aren't boxes per se.  They are names bound to objects.
> so doing something like
>
> a += 1
>
> Actually assigns the name "a" to an entirely new object than the one it
> had before, which, from the interpreters point of view, is in an
> entirely different memory location.

That would be true for locals as well. But as far as I can tell from the 
CPython source code, byte-codes uses an index to represent a local, 
which represents an entry into a linear table.

I can't quite see why that can't be done for global names and for 
attributes too (ie. the names that follow a ".").

Attributes are a more difficult because there can be multiple instances 
of each name, and Python won't know which one is meant, so it needs to 
be resolved at each use.

So in the case of A.B(), Python apparently looks up "B" in the names 
associated with object A (and also, someone said, with the class of 
which A is an instance if the first lookup fails).

I had in mind a different approach, where a table exists for each 
different attribute, which contains an entry for each owner class. 
Usually this table will be small, or will have just one entry, so is 
quick to search.

However, another feature of Python makes that impractical: the ability 
of any instance of a class to have arbitrary sets of attributes. There 
could be millions of such instances, all named "B".

Now, if methods could only be part of a class definition, then with 
A.B() rather than A.B, there will be a limited number of classes that 
could have a method "B", so the short table idea could work.

But then, A.B could be assigned the name of a function, which is then 
called using A.B(), the same as method-calling syntax!

So it looks like Python is stuck with its name lookups.

-- 
Bartc



More information about the Python-list mailing list