Why read-only nested scopes?

Andy Salnikov a_salnikov at yahoo.com
Wed Sep 4 22:47:57 EDT 2002


"Gonçalo Rodrigues" <op73418 at mail.telepac.pt> wrote in message
news:m7ncnugbkm0qghf66qcub6e37b64fesdkq at 4ax.com...
> On 04 Sep 2002 20:38:30 +0200, loewis at informatik.hu-berlin.de (Martin v.
> Löwis) 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?
>
> 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 would have one big drawback. Suppose you wrote one day

def foo():
    x = 2
    def bar():
        y = 3
        def baz():
            global x
            x = 4    # intention here is to change x in foo()

and then few days later you add x to bar():

def foo():
    x = 2
    def bar():
        x = 3       # added code
        y = 3
        def baz():
            global x
            x = 4    # intention here is to change x in foo()

and suddenly it stopped working. You go into debugger, spend couple
of hours and then "suddenly" realize why it should not be this way :)

  Andy.






More information about the Python-list mailing list