Why nested scope rules do not apply to inner Class?

Rhamphoryncus rhamph at gmail.com
Wed Aug 13 15:04:30 EDT 2008


On Aug 13, 11:13 am, "Cousson, Benoit" <b-cous... at ti.com> wrote:
> > There is no point of nested classes because nested classes _are not_
> > supported by python. They are simply an artifact of not actively
> > denying the syntax non-globally. I would fully support a change to the
> > language to actively forbid a class definition that is not
> > module-level.
>
> > > In my case, I'm trying to use a similar approach as XIST's one, meaning
> > using Python class to model hierarchical data. So clearly nested class is
> > a very nice and easy understandable way to do that.
>
> > I don't find that this is clear in anyway. I can't imagine why you'd
> > think a nested class is even useful here, rather than an instance with
> > some understandable attributes. I've seen a lot of places nested
> > classes are used and not one of them that should be been doing it.
>
> > But, on that note, there is a point where a discussion is obviously
> > not going to resolve with either side changing their minds. This is
> > obviously such a case.
>
> I don't think so; my original email was mainly a question. I do agree that they are other ways to do what I'm trying to achieve; there are always several ways to solve an issue.
> Few days ago, I decided to use nested class because I realized that it was the most convenient way to implement my need.
> Since this feature is supported in many languages, I was just surprised that Python did support it only partially, hence my original email.  
>
> Now if you say; it is not supported, don't do that, we will deprecate that feature, fine, I will use an alternative solution.
>
> I was just not aware of that "nested class is evil" group in the Python community. I still not understand why, but if it is the BDFL decision...

It has nothing to do with nested classes, but rather methods trying to
access other methods:

class X(object):
    foo = 42

    def bar(self):
        print foo
        print self.foo
X.foo = 7

When the class is created it *copies* the scope it used, meaning it's
left intact.  "print foo" would print 42, rather than the correct and
desired 7 you get from "print self.foo".  It is this subtle bug, as
well as "There should be one—and preferably only one—obvious way to do
it", that leads to prohibiting nested access to a class's scope.



More information about the Python-list mailing list