Statement local namespaces summary (was Re: python3: 'where' keyword)

Bengt Richter bokr at oz.net
Thu Jan 13 15:39:44 EST 2005


On Thu, 13 Jan 2005 22:41:54 +0300, Andrey Tatarinov <elephantum at dezcom.mephi.ru> wrote:

>Nick Coghlan wrote:
>> Nick Coghlan wrote:
>> 
>>> Semantics
>>> ---------
>>> The code::
>>>
>>> <statement> with:
>>>    <suite>
>>>
>>> translates to::
>>>
>>> def unique_name():
>>>     <suite>
>>>     <statement>
>>> unique_name()
>> I've come to the conclusion that these semantics aren't what I would 
>> expect from the construct. Exactly what I would expect can't really be 
>> expressed in current Python due to the way local name bindings work. The 
>> main thing to consider is what one would expect the following to print:
>> 
>> def f():
>>     a = 1
>>     b = 2
>>     print 1, locals()
>>     print 3, locals() using:
>>         a = 2
>>         c = 3
>>         print 2, locals()
>>     print 4, locals()
>> 
>> I think the least suprising result would be:
>> 
>> 1 {'a': 1, 'b': 2}         # Outer scope
>> 2 {'a': 2, 'c': 3}         # Inner scope
>> 3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope
>> 4 {'a': 1, 'b': 2}         # Outer scope
>
>as for me, I would expect following:
>
>1 {'a': 1, 'b': 2}
>2 {'a': 2, 'b': 2, 'c': 3'}
>3 {'a': 2, 'b': 2, 'c': 3'}
>4 {'a': 1, 'b': 2}

locals() doesn't automatically show everything that is visible from its local scope:

 >>> def foo():
 ...     a = 1
 ...     b = 2
 ...     print 1, locals()
 ...     def inner():
 ...         a = 2
 ...         c = 3
 ...         print 2, locals()
 ...     inner()
 ...     print 4, locals()
 ...
 >>> foo()
 1 {'a': 1, 'b': 2}
 2 {'a': 2, 'c': 3}
 4 {'a': 1, 'b': 2, 'inner': <function inner at 0x02EE8BFC>}

-- unless you actually use it (this is a bit weird maybe?):

 >>> def foo():
 ...     a = 1
 ...     b = 2
 ...     print 1, locals()
 ...     def inner():
 ...         a = 2
 ...         c = 3
 ...         print 2, locals(), 'and b:', b
 ...     inner()
 ...     print 4, locals()
 ...
 >>> foo()
 1 {'a': 1, 'b': 2}
 2 {'a': 2, 'c': 3, 'b': 2} and b: 2
 4 {'a': 1, 'b': 2, 'inner': <function inner at 0x02EE8D4C>}

of course a difference using the new syntax is that 'inner' is not bound to a persistent name.

>
>otherwise that would be impossible to do calculations based on scope 
>variables and "using:" would be useless =), consider example of usage:
>
>current_position = 1
>current_environment # = ...
>current_a_lot_of_other_parameters # = ...
>scores = [count_score(move) for move in aviable_moves] using:
>	def count_score(move):
>		#walking through current_environment
>		return score
No worry, UIAM.

Regards,
Bengt Richter



More information about the Python-list mailing list