Why read-only nested scopes?

Jay O'Connor joconnor at cybermesa.com
Wed Sep 4 20:28:39 EDT 2002


In article <j4d6rt61nd.fsf at informatik.hu-berlin.de>, "Martin v. Löwis"
<loewis at informatik.hu-berlin.de> wrote:

> Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:
> 
>> >Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:
>> >
>> >> So why hasn't this been extended when nested scopes were introduced,
>> >> e.g. by reusing the global directive or some other one?
>> >
>> >I think the main reason is that nobody could propose an acceptable
>> >syntax. Reusing the global directive does not work.
>> 
>> Can you explain why it does not work?
> 
> Consider
> 
> x = 1
> 
> def foo():
>   x = 2
>   def bar():
>     x = 3
>     def baz():
>       global x
>       x = 4
> 
> If you invoke baz(), which of the variables is changed? How do you
> denote that you want to change the others?
> 
> Regards,
> Martin


Why not simply disallow the using of a name already defined in an
enclosing scope? Similar to Smalltalk?

Consider the following:

| y | 
aBlock := [
	| x | 
	y := [	
		| x |
		x := 5
		x
	] value

] value .
^y

Here I'm defining x twice, once inside the outer most block and once
inside the inner most block.  Attempting to execute this (actually,
attempting to compile it) raises an error "x is already defined (perhaps
in an outer block)"

changing the inner x to 'x1' or something solves the problem

This works for instance variables in methods of a class, too.  If an
object has an instance variable named foo...you can't have a method with
a temporary variable named foo also, the compiler will error out with
the above error about foo already being defined

-- 
Jay O'Connor
joconnor at cybermesa.com
http://www.r4h.org/r4hsoftware



More information about the Python-list mailing list