Why we will use obj$func() often

Michael Geary Mike at DeleteThis.Geary.com
Mon Apr 26 12:34:08 EDT 2004


> Greg Ewing wrote:
> > Hang on a minute. Do you literally mean the immediately
> > surrounding function, and not one further out? In
> >
> >    def f():
> >      def g():
> >        def h():
> >          &x = 42
> >        h()
> >      g()
> >      print x
> >
> > does the &x in h refer to the x in f? If it does, then I
> > don't see how you can deduce that in a single pass. If it
> > doesn't, then how do you refer to the x in f from h?

Mark Hahn wrote:
> You cannot.  Yes it literally means the immediately surrounding
> function. In your example, I can't think of any scheme we've
> discussed that accesses x in function f.  Python surely cannot.
>
> I understand this is quite limiting, but it's simple. As always,
> I'm open to suggestions...

Ouch. The way I use nested functions in JavaScript, it's essential to be
able to use names from higher in the scope chain without worrying about how
far up the chain they are.

It's not P*thonic, but JavaScript's solution for this keeps looking better
to me. When you want a local name, you create it with 'var'. When you refer
to a name, it always starts in the current scope and works its way up the
chain until it finds the name.

As with many things, there's a cost and a benefit. The cost is that you
always have to 'var' your local variables. The benefit is that nested
functions and closures become very clean and simple.

-Mike





More information about the Python-list mailing list