Why nested scope rules do not apply to inner Class?

Calvin Spealman ironfroggy at gmail.com
Thu Aug 14 05:40:50 CEST 2008

On Wed, Aug 13, 2008 at 10:49 PM, Carl Banks <pavlovevidence at gmail.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.
> 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):
>        pass
> 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
>    function_that_calls_readline(FileMimicker())
> (Why would I want to clutter up my module's namespace for that silly
> thing?)
> 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

I know every rule has its exceptions. I put "don't nest classes" in
with other similar rules I will claim, where I think its safest to say
"Never do this!", because only then will you know that, should you
actually do it at some point, you've got a reason good enough to break
a "rule".

As for the cluttering of the namespace, I don't buy it. Sure there are
cases to be made to reduce the number of names in any scope, but I
don't see a big advantage here. Its still accessible from the module,
just though the class. I also don't see any examples of nested classes
that wouldn't be useful elsewhere, your example included. For that
matter, your example should just being using StringIO.

Read my blog! I depend on your acceptance of my opinion! I am interesting!
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy

More information about the Python-list mailing list