Objects in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 24 12:00:26 CEST 2012


On Fri, 24 Aug 2012 04:14:27 -0500, Evan Driscoll wrote:

> On 8/23/2012 22:17, alex23 wrote:
>> But Roy's point was that referring to 'a' as a 'variable' makes no
>> sense, as it's not an allocated piece of memory.
> 
> Does the computer just remember what 'a' refers to by keeping notes
> about it in Narnia?

No. The compiler remembers the address of 'a' by keeping notes about it 
somewhere in memory during the compilation process. When you run the 
compiled program, there is no longer any reference to the name 'a'.

(Many compilers give you the option to keep variable names, but that's 
additional debugging data, not an essential part of the execution model.)

The mapping of name:address is part of the *compilation* process -- the 
compiler knows that variable 'x' corresponds to location 12345678, but 
the compiled code has no concept of anything called 'x'. It only knows 
about locations. The source code 'x = 42' is compiled into something like 
'store 42 into location 12345678'. (Locations may be absolute or 
relative.)

In languages with name bindings, the compiler doesn't need to track 
name:address pairs. The compiled application knows about names, but not 
about addresses. The source code 'x = 42' is compiled into something like 
'store 42 into the namespace using key "x"'.

Python gives you no way to peek at an address. It's not even clear what 
the address of the variable would be, because there are *at least three* 
things it could be:

1) the address of the key field in the namespace (where the name lives);

2) the address of the value field in the namespace (where the pointer to 
the object lives);

3) the address of the object itself.

And any of these are free to move around during the lifetime of the 
application. (E.g. in Jython, which runs under the JVM, objects don't 
have a fixed location.)


> Put it this way. If C removed the & operator -- and thus you couldn't
> tell what address a variable (or "variable instance", if you prefer) was
> at -- would "int x;" cease to be a variable?

Not at all. Just because the public interface of the language doesn't 
give you any way to view the fixed locations of variables, doesn't mean 
that variables cease to have fixed locations.



-- 
Steven



More information about the Python-list mailing list