Why read-only nested scopes?

Bengt Richter bokr at oz.net
Thu Sep 5 14:36:09 EDT 2002


On 05 Sep 2002 12:11:45 +0200, loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) wrote:

>Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:
>
>> >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?
>> 
>> I think that crawling up the scope hierarchy and stopping at the first x
>> that one finds (in the above case, the one defined in bar) is a sensible
>> solution. 
>
>This solution is not backwards-compatible. global always refers to
>globals(), programs may rely on that.
>
How about introducing an optional "degree of globalness" for the global declaration? E.g.,

    x = 1
    def foo():
      x = 2
      def bar():
        x = 3
        def baz():
          global(1) x
          x = 4

would go outwards 1 nested scope and thus target the x in bar,
rebinding it from 3 to 4.

plain "global x" would be a backwards-compatible spelling of "global(-1) x",
where the implication of the -1 is to index the last in a list of
scopes starting with global(0) for local and ending with the outermost as
the last in the list, at global(-1). Since all the variants would be syntax
errors now, there would be no old-code breakage.

It might be interesting to let the globals() function take an optional argument
corresponding to the above relative scope parameter. Thus globals(0) would return
the same as locals(), and globals() the same as globals(-1), but in the context of
baz above, globals(1) would return {'x': 3}.

Regards,
Bengt Richter



More information about the Python-list mailing list