Classes in a class: how to access variables from one in another

Chris Rebert clp2 at
Mon Oct 18 18:34:07 CEST 2010

On Mon, Oct 18, 2010 at 8:58 AM, Andreas Waldenburger
<usenot at geekmail.invalid> wrote:
> On Mon, 18 Oct 2010 17:17:52 +0200 Christian Heimes <lists at>
> wrote:
>> [snip]
>> Don't nest classes. Just don't. This might be a valid and good
>> approach in some programming languages but it's not Pythonic.
> Explain!

"Private" classes that are closely related to another class can be
simply be defined at the module level with an appropriate name
indicating the privacy (e.g. _Private vs. Public) rather than inside
their associated class; this saves on indentation and is thus more
pleasant to read.

Also, Python's scoping rules, particularly for class-level scopes,
don't work the way programmers from languages where nested classes are
common would expect:

class Foo(object):
    class FooBar(object):
        def baz(self):
            return SHARED_CONSTANT

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in baz
NameError: global name 'SHARED_CONSTANT' is not defined

Since you must use Foo.SHARED_CONSTANT and similar anyway when you're
in FooBar, nesting FooBar within Foo doesn't really confer any
advantages in the conciseness department.


More information about the Python-list mailing list