Why nested scope rules do not apply to inner Class?

Carl Banks pavlovevidence at gmail.com
Thu Aug 14 04:49:09 CEST 2008

On Aug 13, 11:38 am, "Calvin Spealman" <ironfro... at gmail.com> wrote:
> On Wed, Aug 13, 2008 at 11:32 AM, Cousson, Benoit <b-cous... at ti.com> wrote:
> >> Defining it as a nested class saves you one line
> >> of code, but IMHO makes the result just a bit more cluttered, while
> >> reducing the elegance of reusing the metaclass.
> > The whole point of nested class is to avoid polluting the namespace with classes that are only used locally. So the argument about the elegance of reusing is not very valid in that case.
> 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.

I think that's taking it a little too far.  It's not unreasonable to
throw small, private use classes into the class definition, like so:

class Someting(object):
    class PrivateException(Exception):

And inside function a class definition can make a lot of sense.
Oftentimes I write a quick adaptor class because I want to pass
something to code that expects something else, for instance:

def some_function(lines):
    class FileMimicker(object):
        def __init__(self):
            self.index = 0
        def readline(self):
            line = lines[self.index]
            self.index += 1
            return line

(Why would I want to clutter up my module's namespace for that silly

So I see no good reason for the compiler to disallow nested class
statements; it's occasionally useful and not a common pitfall.

Carl Banks

More information about the Python-list mailing list