[Python-Dev] Nested functions and class scope
Guido van Rossum
guido@python.org
Mon, 13 Nov 2000 07:54:43 -0500
John Max Skaller wrote:
> Guido van Rossum wrote:
> ===============>>>>
> > Other issues that need sorting out:
> >
> > x = 2
> > class C:
> > x = 1
> > C = 'some string'
> > def a(self):
> > print x
> > def b(self):
> > global x
> > x = 3
> >
> > class D(C):
> > C = 'some string'
> > def a(self):
> > C.a(self)
> > print C
> >
> > o = C()
> > o.a()
> > o.b()
> > o.a()
> >
> > o = D()
> > o.a()
> >
> > What would the output look like under your proposal ?
>
> This is a good point! If we considered the class as a nested scope
> here, I think it might break too much code, plus it would allow a new
> coding style where you could reference class variables without a self
> or <classname> prefix. I don't like that prospect, so I'm in favor
> for ruling this out.
> <<<===================
>
> You're missing the point. you can refer to class variables without
> a prefix right now:
>
> class X:
> x = 1
> y = x
>
>
> It would be madness NOT to support lexically scoped nested classes
> as well as functions. But note that these scopes only exist
> when a class is executed, that is, when the class is defined.
> This has NO impact on finding class variables from an instance.
>
> output of above from Vyper:
> --------------------------------------------------------------
> Viperi 2.0.1
> Copyright Maxtal P/L, John Skaller, Australia, 1999
> >>>x = 2
> ...class C:
> ... x = 1
> ... C = 'some string'
> ... def a(self):
> ... print x
> ... def b(self):
> ... global x
> ... x = 3
> ...
> >>>class D(C):
> ... C = 'some string'
> ... def a(self):
> ... C.a(self)
> ... print C
> ...
> >>>o = C()
> ...o.a()
> ...o.b()
> ...o.a()
> ...
> 1
> 3
> >>>o = D()
> ...o.a()
> ...
> Error Near line 4
>
> Uncaught Python Exception at top level!!
> .. Kind: Instance of AttributeError
> .. Attributes:
> args --> Cannot find attribute of "some string" "a"
>
> Traceback (innermost first)
> File: <string> Line: 4
> <cannot get line from file>
> File: <string> Line: 2
> <cannot get line from file>
>
> --
> John (Max) Skaller, mailto:skaller@maxtal.com.au
> 10/1 Toxteth Rd Glebe NSW 2037 Australia voice: 61-2-9660-0850
> checkout Vyper http://Vyper.sourceforge.net
> download Interscript http://Interscript.sourceforge.net
Looks like you are missing the point. Of course I want to keep the
class as a local scope *inside the class def*. But I need it out of
the way when executing methods. The example code should print
2 # a() references global x, not C.x
3 # global x got set to three by b()
2 # C refers to global class C
<class C ...> # ditto
I agree that this is surprising. But I believe it would break too
much code if we implemented your (simpler) scheme.
--Guido van Rossum (home page: http://www.python.org/~guido/)