[Python-ideas] binding vs rebinding

Steven D'Aprano steve at pearwood.info
Fri Feb 6 14:39:18 CET 2009


spir wrote:
> Le Fri, 06 Feb 2009 08:31:58 +1100,
> Ben Finney <ben+python at benfinney.id.au> a écrit :
> 
>>> I wonder why there is no difference in syntax between binding and
>>> rebinding. Obviously, the semantics is not at all the same, for
>>> humans as well as for the interpreter:  
>>> * Binding: create a name, bind a value to it.
>>> * Rebinding: change the value bound to the name.  
>> That's not obvious. The semantics could just as well be described as:
>>
>>   * Binding: bind this name to that value.
>>   * Rebinding: bind this name to that value.
> 
> You are right do describe it like that. I agree that the point of view is not wrong. However,
> 
> * At the interpreter level, as far as I know, rebinding does not create the name like if it was unknown. (Note that a similar issue happens with dicts.)

Both binding and rebinding actions are identical.

 >>> x = 5
 >>> import dis
 >>> dis.dis( compile("x=3  # rebinding", '', 'single') )
   1           0 LOAD_CONST               0 (3)
               3 STORE_NAME               0 (x)
               6 LOAD_CONST               1 (None)
               9 RETURN_VALUE
 >>> del x
 >>> dis.dis( compile("x=3  # new binding", '', 'single') )
   1           0 LOAD_CONST               0 (3)
               3 STORE_NAME               0 (x)
               6 LOAD_CONST               1 (None)
               9 RETURN_VALUE


Whatever implementation difference there may be is transparent at the 
interpreter level.


> * At the programmer level, changing the value associated to a name is really a different action than introducing and giving an initial value to a new symbol. For me, *this* is the relevant point: even if the language would behave "behind the scene" the same way in both cases. This is implantation concern.

I disagree. At the programmer level, x=5 is the same thing whether x 
already exists or not.


> A pertinent objection has been raised already in the case of loops:
> 
> for item in container:
> 	# temp symbol
> 	foo = func(item)
> 	# process
> 	do_stuff
> 
> Conceptually, there is a foo for each item. Obviously, we cannot express that properly, because the loop's body is the same for each iteration. The issue here lies in the fact that a loop does not introduce a local namespace, while this is precisely what we *mean* when defining such as utility variable as foo.

Speak for yourself. When I use a for loop, I do not expect or want it to 
create a new namespace.

> In other words: there is a distortion between language semantics and modelizing semantics.

I disagree. I think the language semantics match precisely the semantics 
of name binding as I expect it.


-- 
Steven




More information about the Python-ideas mailing list