explicit variable scoping

David MacQuigg dmq at gain.com
Mon Mar 22 13:53:23 EST 2004


On Mon, 22 Mar 2004 03:19:46 -0800 (PST), Eyal Lotem
<gnupeaker at yahoo.com> wrote:

[snip motivation for changing the scope rules]

>A) Only get rid of the assignment-makes-local
>heuristic, by changing the meaning of the "global"
>keyword:
>
>def f():
>	global.a = 1 # Assigns to the module.a
>	a = 2 # Assigns to a local variable
>
>This allows accessing globals, and IMO serves for
>better explicitness about variables which is very
>desirable and consistent with instance variable
>access.

I'm not seeing much advantage over:
global a; a = 1
When you say "accessing" globals, we need to distinguish between
"referencing" and "setting".  Referencing globals is already
automatic. Setting globals needs special syntax.  For the few times I
need to set global variables, I'm not feeling much need for
streamlining the existing syntax.  Most of my use of global variables
is global within a named module.  In this case, I refer explicitly to
the module name.  e.g. M1.a = 1  So the improvement above would apply
only to the case where you need to set global variables in the main
module.

[snip how to migrate old code]

>B) Create a hierarchy of "locals" for nested scopes,
>which are accessible via an overloaded or new keyword
>thus:
>
>I)
>	b = 1
>	def f():
>		a = 2
>		def g():
>			global.a = 3
>			global.global.b = 4

Ugh!!

>II)
>	b = 1
>	def f():
>		a = 2
>		def g():
>			parent.a = 3
>			global.b = 4
>

What about aunts and uncles? :>)

I'm not feeling much need to set variables other than local or global,
but I can see where this might be useful to someone.  The tradeoff is
convenience for a few vs a mess from lots of users who will abuse the
flexibility.  (The same kind of tradeoff as with the GOTO statement.)
I would not give up *essential* flexibility for this reason, but we
are talking here of just a convenience.

If we want to set variables in intermediate scopes, I would prefer a
syntax like:

	b = 1
	def f():
		a = 2
		def g():
			global.f.a = 3
			global.b = 4

Of course, this means we also have to allow functions to have
attributes.

If we are going to make one more change in the scope rules, I would
like to see a grand simplification -- the current rules are good, just
extend them to *any* nested scopes.  If I set up a hierarchy of 7
nested classes, I should be able to reference variables at a higher
level without fully qualified names.  Again, this is just a
convenience.  Mainly, it would make teaching Python simpler.

-- Dave




More information about the Python-list mailing list