Nested function scope problem

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Jul 27 16:26:28 EDT 2006


Gerhard Fiedler a écrit :
> On 2006-07-27 14:15:34, Dennis Lee Bieber wrote:
> 
> 
>>>In a language like C the name doesn't hold anything either. The name is
>>>just a way for refering to a memory space which will hold something. 
>>>
>>
>>	Except for one difference... In C (and most other languages) that
>>memory space is FIXED -- name "X" ALWAYS refers to memory space "Y".
> 
> 
> Not really fixed, at least not for local variables. They sit at variable
> places, which can be (and usually are) different for every invocation of a
> function. Maybe "stack-fixed"...
> 
> Not sure this is relevant, but I felt it needed to be said :)
> 
> 
> 
>>	In Python, even the location of the "name" may vary -- if you "del
>>name" then do some operations and rebind "name", the new "name" itself
>>could be somewhere else in memory.
> 
> 
> In this respect, a Python var is similar to a C pointer var. The same thing
> you are describing here can be done with a C pointer. Allocate storage
> ("bind" it) and have a pointer referencing it. Do something with it.
> Deallocate it ("del it"). Allocate other storage and have the same pointer
> referencing it ("rebind it"). The referenced area is somewhere else now
> (usually). 

Yes, Python references and C pointers are closely related.

But  a C pointer (I mean the pointer itself, not what it points to) is 
still a C variable. It has a 'lifetime-fixed' memory address - 
deallocating the memory block whose address is stored in the pointer and 
assigning NULL to the pointer won't change the pointer's address, nor 
make the pointer variable disappear from the current scope FWIW - and an 
'immediate' value - which is either garbage, NULL or a (possibly invalid 
!-) memory address.

While in Python, deleting a name *really* delete the name from the 
current namespace - but not necessarily the object that was bound to the 
name:

Python 2.4.1 (#1, Jul 23 2005, 00:37:37)
[GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on 
linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> a = []
 >>> del a
 >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
NameError: name 'a' is not defined
 >>> a = []
 >>> id(a)
1078043756
 >>> b = a
 >>> id(b)
1078043756
 >>> del a
 >>> b
[]
 >>> id(b)
1078043756
 >>>

NB:  in CPython, id(<somename>) returns the address of the object bound 
to <somename>.

HTH



More information about the Python-list mailing list